Skip to content

C# WebAPI 中启用 CORS

使用 Vue.js 本地开发时,发现 post 请求变成了 OPTIONS 请求。求助度娘🐾🐾vue resource 的 $.http.post 方法怎么会变成 OPTIONS 方法?


简单来说,就是“非简单请求”在跨域时,浏览器会默认自动帮你发一个 OPTIONS 请求,到服务器端请求服务器确认该请求的合法性,服务器端必须得有相应的路由处理该请求,并认真返回 200 响应,然后浏览器才会再次发出正常的、你需要的请求。


原来是跨域访问 API 导致的。本地 Vue 工程使用的 8080 端口,而本地的 WebAPI 使用的是 18184 端口。

知道原因就好解决了,允许 WebAPI 跨域访问就行了。参考下面的文章:

  1. ASP.NET Web API 自身对 CORS 的支持:从实例开始
  2. WebAPI CORS 支持跨域 POST

WebAPI 中启用 CORS 的具体步骤

1. 安装了 Microsoft.AspNet.WebApi.Cors

2. Global.asax 的 Application_Start 方法中启用 CORS

csharp
public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configuration.EnableCors();         //其他操作
    }
}

3. 在 Controller 中配置具体的 CORS

csharp
[EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
public class ContactsController : ApiController
{
}

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.