user3881465
user3881465

Reputation: 269

Ajax CORS call not working for application/json

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?

Upvotes: 1

Views: 1833

Answers (1)

Emmanuel
Emmanuel

Reputation: 11

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
    }
}

}

Upvotes: 1

Related Questions