Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method json json

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.aspxAnd: http://enable-cors.org/#how-iis7


I ran into a problem where the browser refused to serve up content that it had retrieved when the request passed in cookies (e.g., the xhr had its withCredentials=true), and the site had Access-Control-Allow-Origin set to *. (The error in Chrome was, "Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.")

Building on the answer from @jgauffin, I created this, which is basically a way of working around that particular browser security check, so caveat emptor.

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute{    public override void OnActionExecuting(ActionExecutingContext filterContext)    {        // We'd normally just use "*" for the allow-origin header,         // but Chrome (and perhaps others) won't allow you to use authentication if        // the header is set to "*".        // TODO: Check elsewhere to see if the origin is actually on the list of trusted domains.        var ctx = filterContext.RequestContext.HttpContext;        var origin = ctx.Request.Headers["Origin"];        var allowOrigin = !string.IsNullOrWhiteSpace(origin) ? origin : "*";        ctx.Response.AddHeader("Access-Control-Allow-Origin", allowOrigin);        ctx.Response.AddHeader("Access-Control-Allow-Headers", "*");        ctx.Response.AddHeader("Access-Control-Allow-Credentials", "true");        base.OnActionExecuting(filterContext);    }}