How to enable CORS in Asp.Net MVC5

时间秒杀一切 提交于 2019-12-11 15:59:02

问题


I am running Angular 6 in my local and getting CROS error when invoking MVC controller action method.

I tried to fix this by adding below line of code in my .net application's web.config file. But still getting same error.

<httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

I do not want to run a browser by disabling web security also I do not want to create a class since only to run in my local I need to enable the CORS.

Is there any simplest of way to fix this in Web.config or Global.asax file.


回答1:


CORS requires 3 headers to work correctly.

A great resource for remembering how CORS works is The MDN Documentation.

The header you have included will allow all origins to make a request. But does not specify which requests they are allowed to make, and so, all requests are blocked.
To allow all origins to make specific requests you need to include the Access-Control-Allow-Methods header, which tells the browser which requests the web server is allowing on that endpoint.

Depending on how your requests are formed, you may also need to include the Access-Control-Allow-Headers header, which tells the browser which headers it is allowed to send to the web server on that endpoint.

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400

Using all this, the correct configuration for your web.config would be:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*"/>
                <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/>
                <add name="Access-Control-Allow-Headers" value="Content-Type"/>
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

Which will allow you to access that endpoint using either POST or GET. The Access-Control-Max-Age header will tell your browser to cache these results for that many seconds, for performance reasons.


Also please be sure to not include this configuration in any production system you may be running. It's always best to enable CORS explicitely for each action / controller that may need it.



来源:https://stackoverflow.com/questions/57307454/how-to-enable-cors-in-asp-net-mvc5

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