1

My following code is working fine and I am able to call API

$.ajax({
    url: "http://localhost:57786/mvc/create",
    method: "POST",            
    data: { FirstName: "ABC", LastName: "XYZ" },
    success: function (data) {
        alert("Success");
    },
    error: function (statusText, error) {
        alert("Error");
    }
});

But following code is not working and I am not able to call API

    $.ajax({
        url: "http://localhost:57786/mvc/create",
        method: "POST",
        data: JSON.stringify({ FirstName: "ABC", LastName: "XYZ" }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert("Success");
        },
        error: function (statusText, error) {
            alert("Error");
        }
    });

Here is API code

[EnableCors("*","*","*")]
public class MVCController : Controller
{
    // POST: MVC/Create
    [HttpPost]
    public ActionResult Create(MyData value)
    {
         //My Code
    }
}

I am getting response The response had HTTP status code 404.

Why Ajax call is failing when I use contentType to application/json?

user3881465
  • 239
  • 2
  • 5
  • 19
  • Exactly in what way is it failing? What’s the exact error message the browser is logging in the devtools console? What’s the HTTP status code of the response? Is it 200 or 204? Or is it 405 or some 5xx code? You probably want to use https://stackoverflow.com/q/45890667/441757 to edit/update your question to add those details. To get the status code you need to go into the Network pane in your browser devtools and inspect the response there and copy the status code. You’ll see there that the browser has sent an OPTIONS request. That’s what you need to examine. – sideshowbarker Aug 25 '17 at 23:53
  • See https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141 for some explanation. What’s happening is that adding the 'contentType: application/json' header to the POST request causes your browser to do a COR preflight OPTIONS request before trying the POST. So the backend code on the server you’re sending the request to must be have code for correctly handling that OPTIONS request. – sideshowbarker Aug 25 '17 at 23:56
  • You might also need the "dataType" option on the ajax request like this: dataType:"json" – John Maloney Aug 25 '17 at 23:58
  • @sideshowbarker : I am getting status code 404. Can you tell me what I need to do so that server code can handle OPTION request ? – user3881465 Aug 26 '17 at 00:04
  • Anybody has solution for this question ? – user3881465 Aug 29 '17 at 22:53

1 Answers1

1

Had similar issues and i fixed it by adding some configurations in the system.webserver in web.config or you can write it as a custom filter attribute and then register it in filterconfig.cs in App_start folder.

 <system.webserver>
       <httpProtocol>
        <customHeaders>
           <add name="Access-Control-Allow-Origin" value="*" />
           <add name="Access-Control-Allow-Headers" value="Content-Type" />
         <add name="Access-Control-Allow-Methods" value="GET, POST, PUT,DELETE,OPTIONS"/>
        </customHeaders>
     </httpProtocol>
 </system.webserver>

<--this is for the web,config-->

or for the filterconfig.cs you can write a custom filter and override the ActionFilterAttribute but note that the challenge with this is that any action such as /token to generate an authorization token might fail because it does not satisfy the onActionExecuting method, so maybe you might want to go with the web.config

   public class CustomHeaderAttributeFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //add in your custom headers
        filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
        filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS");

        base.OnActionExecuting(filterContext);
    }

    public void OnException(ExceptionContext filterContext)
    {
        //do some cool exception handling here
    }
}

}

Emmanuel
  • 11
  • 4