且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用多个来源的PUT和DELETE请求时,如何解决ASP.NET Web API CORS预检问题?

更新时间:2023-02-15 12:38:00

我能够通过进一步自定义Global.asax.cs中的Application_BeginRequest方法来解决我的问题,如下所示:

I was able to solve my problem by further customizing the Application_BeginRequest method in Global.asax.cs, like this:

protected void Application_BeginRequest()
{
    if (Request.HttpMethod == "OPTIONS")
    {
        Response.StatusCode = (int)HttpStatusCode.OK;
        Response.AppendHeader("Access-Control-Allow-Origin", Request.Headers.GetValues("Origin")[0]);
        Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        Response.AppendHeader("Access-Control-Allow-Credentials", "true");
        Response.End();
    }
}

此代码的作用是将丢失的标头添加到导致预检错误的OPTIONS响应(预检请求)中.由于调用Web API的来源不同,因此我使用Request.Headers.GetValues("Origin")[0])来动态设置响应中的来源.

What this code does is add the missing headers to the OPTIONS response (preflight request) that were causing the preflight error. Since I have different origins calling my web API, I'm using Request.Headers.GetValues("Origin")[0]) to set the origin in the response dinamically.

在WebApiConfig.cs中,我仍然指定了不同的来源,但在标头和方法上使用了通配符,并将SupportsCredentials设置为true,如下所示:

In the WebApiConfig.cs I still specified the different origins but used wildcards on the headers and methods, as well as setting the SupportsCredentials to true, like this:

var cors = new EnableCorsAttribute("http://localhost:63342,http://localhost:63347,http://localhost:63345", "*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);

此外,如果像我一样使用AngularJS,则必须将$ http配置为使用凭据.可以像这样全局配置:

Also, if you're using AngularJS like I am, you must configure $http to use credentials. This can be configured globally like this:

angular
.module('Application')
.config(['$httpProvider',
    function config($httpProvider) {
        $httpProvider.defaults.withCredentials = true;
    }
]);

就是这样.这解决了我的问题.如果仍有其他问题,我建议您阅读以下出版物,这些出版物有助于我找到答案:

And that's it. This solved my problem. If someone else is still having problems, I recommend reading the following publications, which helped me reach my answer:

  • http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
  • https://evolpin.wordpress.com/2012/10/12/the-cors/
  • AngularJS $http, CORS and http authentication
  • AngularJS performs an OPTIONS HTTP request for a cross-origin resource
  • AngularJS POST Fails: Response for preflight has invalid HTTP status code 404