Reputation: 3726
I am calling .net core action via ajax request. It's not even waiting for the return statement but as soon as I am calling Auth0 management api it's returning error.
[HttpPost]
public async Task<IActionResult> Create([FromBody]ConnectionCreateRequest model)
{
try
{
var result = await _managementApiClient.Connections.CreateAsync(model);
return Ok();
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
It's returning error after result statement.
Here is the ajax call:
$.ajax({
type: "POST",
url: '@Url.Action("Create", "Connection")',
contentType: "application/json charset=utf-8",
data: JSON.stringify(model),
success: function (result) {
alert('Connections has been created successfully');
},
error: function (result, err) {
alert(err);
},
complete: function () {
hideLoadingGif();
}
});
});
What am I doing wrong?
Upvotes: 2
Views: 2478
Reputation: 1597
The problem is that in $.ajax method you didn't specify dataType property. In this case $.ajax makes an "intelligent guess" based on response content type:
dataType (default: Intelligent Guess (xml, json, script, or html)) The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.
Ok()
method in .net core returns empty response without MIME type specified in response header. That's why $.ajax triggers error callback with statusText "parseerror"
.
The solution is:
"text"
, and $ajax will accept empty reponse and trigger success callbackJson(true)
or Json(null)
for successful response, and $.ajax will automatically recognize it as json response and trigger success callback.Documentation for $.ajax dataType option for json response:
As of jQuery 1.9, an empty response is also rejected if dataType is json; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.
Upvotes: 4
Reputation: 1614
The problem is that your Controller is returning Content in the exception Which is a 200 status code result in the terms of IAction Result.
Your controller is catching the exception correctly but still returning a 200 because of the Content return Statement.
Upvotes: 0