Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable cross origin requests in ASP.NET MVC [duplicate]

I am trying to create a web application which works with cross-origin requests (CORS) in MVC 5. I have tried everything without any result.

With an attribute

public class AllowCrossSiteJsonAttribute: ActionFilterAttribute {     public override void OnActionExecuting(ActionExecutingContext filterContext)     {             filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");          base.OnActionExecuting(filterContext);     } } 

With EnableCors attribute

 [EnableCors("*")] 

Nothing works I'm starting to think that it is impossible

like image 563
Petar Bechev Avatar asked Oct 17 '16 05:10

Petar Bechev


People also ask

How do I enable cross-origin requests in asp net app?

You can enable CORS per action, per controller, or globally for all Web API controllers in your application. To enable CORS for a single action, set the [EnableCors] attribute on the action method.

What is CORS in ASP NET MVC?

CORS Stands for Cross-Origin Resource Sharing. It is a W3C Standard that allows a server to relax the same-policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others.


1 Answers

Add the configuration setting in your web.config file to set the value for Access-Control-Allow-Origin in customHeaders like this -

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

You would like to visit this and this for more details and some other options.

like image 118
Yogi Avatar answered Oct 11 '22 00:10

Yogi