OWIN WebAPI 2 jQuery Ajax getting NetworkError

391 Views Asked by At

May I know the reason why the code below returns NetworkError when I try to invoke the WebAPI using jQuery Ajax? The Web Method was called successfully, but giving out error after it returned.

I can access the Web Method using IE if I change the access to HttpGet.

So it must be something wrong with jQuery Ajax. Hoping someone would help.

$.ajax({
type: "POST",
async: false,
url: "http://localhost:5000/API/Test",
xhrFields: { withCredentials: true },
data: JSON.stringify(Params),
contentType: "application/x-www-form-urlencoded",
success: function (msg) {
},
error: function (XHR, errStatus, errorThrown) {
});

[Route("API/Test"), HttpPost]
public string Test()
{
JsonConvert.SerializeObject(new { Test = "Test Message" });
}
2

There are 2 best solutions below

2
On

Some changes are needed to make this work

1. Content-type

You are using the content type of "application/x-www-form-urlencoded" but sending the data as a JSON string. Change the content type to "application/json". The Api will by default deserialize the request body from json so it should work.

2. No input in the Api signature

The Test() does not read anything from the request body. Add an object as parameter which matches the object sent by the client.

3. No return

The Api method does not return a string as the signature promise.

Final result

$.ajax({
    type: "POST",
    async: false,
    url: "http://localhost:5000/API/Test",
    xhrFields: { withCredentials: true },
    data: JSON.stringify(Params),
    contentType: "application/json",
    success: function (msg) {
        console.log(msg);
    },
    error: function (XHR, errStatus, errorThrown) {
        console.log(errStatus);
    });

[Route("API/Test"), HttpPost]
public string Test(RequestBodyDTO body)
{
    return JsonConvert.SerializeObject(new { Test = "Test Message" });
}
0
On

I have found the answer to my own question.

Even when I am calling from the same PC (but using jQuery Ajax), I need to add:

[AllowAnonymous] // To the controller

and

appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // To the HttpConfiguration before any routes