我正在通过 ajax 请求调用 .net core 操作。它甚至没有等待 return 语句,但只要我调用 Auth0 管理 api,它就会返回错误。
[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);
}
}
结果语句后返回错误。
这是 ajax 调用:
$.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();
}
});
});
我做错了什么?
最佳答案
问题是在 $.ajax 方法中您没有指定 dataType属性(property)。在本例中,$.ajax 根据响应内容类型进行“智能猜测”:
.net core 中的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()
方法返回空响应,响应头中未指定 MIME 类型。这就是 $.ajax 使用 statusText "parseerror"
触发错误回调的原因。
解决办法是:
- 将 $.ajax dataType 选项设置为
"text"
,$ajax 将接受空响应并触发成功回调 - 在.net core中返回
Json(true)
或Json(null)
表示成功响应,$.ajax会自动识别为json响应并触发成功回调。
$.ajax dataType option 的文档对于 json 响应:
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.
关于javascript - Ajax 请求返回错误,而 .net core Controller 返回 200 Ok,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52538660/