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