DCSIMG
<-- +1 script --> October 2011 - Posts - .Net && Beyond

.Net && Beyond

Taking about .NET and much more

October 2011 - Posts

Enable cross origin request with ASP.NET MVC

As you know you can’t make an Ajax cross domain request. The browser block this kind of requests. To enable Cross-Origin Requests (CORS) you need to add some headers to the server response: “Access-Control-Allow-Origin” and “Access-Control-Allow-Methods”.

So I made a MVC filter that will allow cross domain calls:

public class AllowCrossDomain : ActionFilterAttribute
{
    public const string AllDomains = "*";
 
    private readonly string[] _allowMethods;
    private string _allowOrigin;
 
    public AllowCrossDomain()
        : this(null, null)
    {
 
    }
 
    public AllowCrossDomain(string allowOrigin, params string[] allowMethods)
    {
        _allowMethods = allowMethods;
        _allowOrigin = allowOrigin;
 
        if (string.IsNullOrWhiteSpace(_allowOrigin))
        {
            _allowOrigin = AllDomains;
        }
        if (_allowMethods == null || _allowMethods.Length == 0)
        {
            _allowMethods = new[] { "GET" };
        }
    }
 
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", _allowOrigin);
        filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", string.Join(", ", _allowMethods));
        filterContext.HttpContext.Response.Headers.Add("Access-Control-Max-Age", "86400");
    }

To use it just put it on a method on controller:

[AllowCrossDomain]
public ActionResult Index()
{
    return Json(new {sample="a sample data",crossDomain="you can read it from cross domain"})
}

Simple…

A few things before you try this:

1. “Cassini” doesn’t support this kind of headers you will need to run it on IIS \ IIS Express

2. CROS are supported only by modern browsers FF 3.6+ all chrome browsers, modern smart phones…

3. In order to enable it on IE you need to change the security settings:

 

you can read more about CROS here: http://www.w3.org/TR/cors/

 

Keep Writing, Compiling, and Debugging

Alon Nativ

Posted: Oct 05 2011, 02:08 AM by Alon Nativ | with 6 comment(s)
תגים:, , ,