Tuesday, January 28, 2014

How to solve XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin error in ASP.NET MVC 4

This error may occur when you try to communicate between different domain using AJAX calls. To solve the issue we need set up the WEB API to return correct headers.

Create a class called CrossDomainActionFilter inherited by ActionFilterAttribute.

public class CrossDomainActionFilter : ActionFilterAttribute
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            bool needCrossDomain = true;

            if (needCrossDomain)
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");


[AcceptVerbs("GET", "POST")]
    public object GetTest()
         rep = new ChatRepository();
        chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);

        System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
            Data = box,
            JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet

        return jsonResult.Data;

No comments:
Write comments
Recommended Posts × +