somu somu - 1 year ago 714
Javascript Question

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource MVC 5

I have created one project in MVC 5. I want to call one action method from jquery. This action will return json object. In jQuery ajax id

dataType: 'jsonp',

but throwing error in browser. If I set

dataType: 'json'


Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:.....

I set attribute in web config and application begin request like

void Application_BeginRequest(object sender, EventArgs e)
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");


<remove name="FormsAuthentication"/>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />

My controller action

public class ProductApiController : Controller
public JsonResult GetProductJson(int Productid, string Key)
return this.Json(new { Errorcode = "1", data = "data json success" }, JsonRequestBehavior.AllowGet);

My jQuery request

type: 'GET',
url: 'http://--------------',
cache: false,
data: "id:2",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
error: function (response) {


Answer Source

Add it in filter

  public override void OnActionExecuting(ActionExecutingContext filterContext)
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, origin, authorization, accept, client-security-token");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Max-Age", "1000");

Controller should be

    public JsonResult Getvalue(string Key, int id)
        Result objresult = new Result();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download