somu somu - 7 months ago 438
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'


throwing


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");
}


in
web.config
:

<system.webServer>
<modules>
<remove name="FormsAuthentication"/>
</modules>
<httpProtocol>
<customHeaders>
<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" />
</customHeaders>
</httpProtocol>
</system.webServer>


My controller action

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


My jQuery request

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


Thanks

Answer

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");
        base.OnActionExecuting(filterContext);
    }

Controller should be

  [AllowCrossSiteJson]
    public JsonResult Getvalue(string Key, int id)
    {
        Result objresult = new Result();
        try
        {