Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method
For plain ASP.NET MVC Controllers
Create a new attribute
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
Tag your action:
[AllowCrossSiteJson]
public ActionResult YourMethod()
{
return Json("Works better?");
}
For ASP.NET Web API
using System;
using System.Web.Http.Filters;
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
base.OnActionExecuted(actionExecutedContext);
}
}
Tag a whole API controller:
[AllowCrossSiteJson]
public class ValuesController : ApiController
{
Or individual API calls:
[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
...
}
For Internet Explorer <= v9
IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).
Download it using nuget corsproxy
and follow the included instructions.
Blog post | Source code
If you are using IIS 7+, you can place a web.config file into the root of the folder with this in the system.webServer section:
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
See: http://msdn.microsoft.com/en-us/library/ms178685.aspx And: http://enable-cors.org/#how-iis7