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.
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.Using all this, the correct configuration for your web.config would be:
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.