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", "*");
}
base.OnActionExecuted(actionExecutedContext);
}
}
[AcceptVerbs("GET", "POST")]
[CrossDomainActionFilter]
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;
}
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
Subscribe to:
Post Comments (Atom)
No comments:
Write comments