Issues with CORS in ASP.NET

我与影子孤独终老i 提交于 2019-11-29 00:21:53

I believe that your 'random' issue occurs because you are not handling the preflight Options requests for PUT and Delete verbs.

For the two verbs mentioned above an extra request is generated, Options, to which Web API needs to respond in order to confirm that it is indeed configured to support CORS.

To handle this, all you need to do is send an empty response back. You can do this inside your actions, or you can do it globally like this:

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

This extra check was added to ensure that old APIs that were designed to accept only GET and POST requests will not be exploited. Imagine sending a DELETE request to an API designed when this verb didn't exist. The outcome is unpredictable and the results might be dangerous.

Also, in web.config, you should specify the methods instead of using *

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
 </httpProtocol>

There is no ambiguity with CORS, you have a few cases that you need to think about

1- if you want to enable CORS for your Web APIs only use "Microsoft.AspNet.WebApi.Cors" library.

2- if you want to enable CORS for the whole website (including the Web APIs, SignalR, ..etc ) use "Microsoft.Owin.Cors" library.

using any library from the above 2 will definitely work and cors will be enabled, now if you want to configure the urls, you can do that from your database/config file, so when your application starts the url that you pass to the EnableCors for example can come from the database/config file, but the bottom line is to avoid adding any cors headers to the web.config.

To know to enable CORS for your Web API, you can have a look to my article here, which enables CORS for the Web APIs and use it from AngularJS client.

Hope that helps.

For anyone reading this, this may help.

Even with the following startup code

var cors = new EnableCorsAttribute("*", "*", "GET, POST, PUT, DELETE, OPTIONS");
config.EnableCors(cors);

I had to explcitly add the verbs to the Web Api action method:

[Route("sanity")]
[HttpOptions]
[HttpPost]
public List<PostImportView> Sanity(SanityFilter filter)
{
    ....

Pretty pointless and annoying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!