How to enable cross origin requests in ASP.NET MVC
I've had success using the OWIN CORS implementation (nuget Microsoft.Owin.Cors) to enable Cors for MVC Controllers and Owin middleware, in addition to ApiControllers. Microsoft.AspNet.WebApi.Cors (using config.EnableCors()
and the [EnableCors]
attribute) only seems to work with ApiControllers.
See http://benfoster.io/blog/aspnet-webapi-cors for sample code.
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.
What I think is the most convenient is to create your own class like this :
with the following code in it :
using System;
using System.Web.Mvc;
public class AllowCrossSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
base.OnActionExecuting(filterContext);
}
}
After this it's let you use this decorator on a method or on the whole controller
You should be able to see that in your response header after this procedure
Thank's to this response