ASP.NET中CORS的问题

时间:2020-12-17 03:30:44

I have this App where I would like to set my custom headers in the Web.Config, alas this is not always fool proof.

我有这个应用程序,我想在Web.Config中设置我的自定义标题,唉,这并不总是万无一失。

  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
  </customHeaders>

The above set and iterations of it such as

上面的设置和它的迭代如

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

has not worked worked for me in all scenario's. As of now this setting works in about 50% of the test machines and gives 405 Method Not Allowed in others.

在所有场景中都没有为我工作过。截至目前,此设置适用于大约50%的测试机器,并且在其他测试机器中提供405方法不允许。

The alternative is set this in WebApiConfig.cs and uncomment the custom headers in Web.config.

替代方法在WebApiConfig.cs中设置,并取消注释Web.config中的自定义标头。

//Web API Cross origin requests - Enable
  var cors = new EnableCorsAttribute("*", "*", "*");
  config.EnableCors(cors);

Why is there so much ambiguity in this and how do I know for sure where CORS will work all the time? I am really interested in setting CORS on Web.config only as I would like the flexibility of modifying it in the deployed version.

为什么这里有这么多含糊不清的地方?我怎么知道CORS一直在哪里工作?我真的很感兴趣在Web.config上设置CORS,因为我希望在部署版本中灵活地修改它。

3 个解决方案

#1


13  

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

我相信你的'随机'问题是因为你没有处理PUT和删除动词的预检选项请求。

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.

对于上面提到的两个动词,会生成一个额外的请求,即Web API需要响应的请求,以确认它确实配置为支持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.

添加了此额外检查以确保不会利用旨在仅接受GET和POST请求的旧API。想象一下,当此动词不存在时,向设计的API发送DELETE请求。结果是不可预测的,结果可能是危险的。

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

另外,在web.config中,您应该指定方法而不是使用*

<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>

#2


0  

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

CORS没有任何含糊之处,您需要考虑一些案例

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

1-如果要为Web API启用CORS,请仅使用“Microsoft.AspNet.WebApi.Cors”库。

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

2-如果要为整个网站(包括Web API,SignalR,..等)启用CORS,请使用“Microsoft.Owin.Cors”库。

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.

使用上面2中的任何库肯定会工作,并且将启用cors,现在如果你想配置url,你可以从你的数据库/配置文件中做到这一点,所以当你的应用程序启动你传递给EnableCors的url时示例可以来自数据库/配置文件,但最重要的是避免向web.config添加任何cors头。

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.

要知道如何为您的Web API启用CORS,您可以查看我的文章,它为Web API启用CORS并从AngularJS客户端使用它。

Hope that helps.

希望有所帮助。

#3


0  

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:

我不得不将动词添加到Web Api动作方法中:

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

Pretty pointless and annoying

非常无意义和烦人

#1


13  

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

我相信你的'随机'问题是因为你没有处理PUT和删除动词的预检选项请求。

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.

对于上面提到的两个动词,会生成一个额外的请求,即Web API需要响应的请求,以确认它确实配置为支持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.

添加了此额外检查以确保不会利用旨在仅接受GET和POST请求的旧API。想象一下,当此动词不存在时,向设计的API发送DELETE请求。结果是不可预测的,结果可能是危险的。

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

另外,在web.config中,您应该指定方法而不是使用*

<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>

#2


0  

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

CORS没有任何含糊之处,您需要考虑一些案例

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

1-如果要为Web API启用CORS,请仅使用“Microsoft.AspNet.WebApi.Cors”库。

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

2-如果要为整个网站(包括Web API,SignalR,..等)启用CORS,请使用“Microsoft.Owin.Cors”库。

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.

使用上面2中的任何库肯定会工作,并且将启用cors,现在如果你想配置url,你可以从你的数据库/配置文件中做到这一点,所以当你的应用程序启动你传递给EnableCors的url时示例可以来自数据库/配置文件,但最重要的是避免向web.config添加任何cors头。

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.

要知道如何为您的Web API启用CORS,您可以查看我的文章,它为Web API启用CORS并从AngularJS客户端使用它。

Hope that helps.

希望有所帮助。

#3


0  

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:

我不得不将动词添加到Web Api动作方法中:

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

Pretty pointless and annoying

非常无意义和烦人