How to enable CORS in Asp.Net MVC5

2019-08-17 15:04发布

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条回答
再贱就再见
2楼-- · 2019-08-17 16:01

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.

查看更多
登录 后发表回答