【发布时间】:2019-06-11 19:29:50
【问题描述】:
我有一个新的 Mvc Core 应用程序。我使用 jquery 对我的控制器进行 ajax 调用。如果控制器中出现异常,我正在尝试返回错误消息。这是我的代码示例:
public async Task<IActionResult> UpdateAllocations([FromBody]AllocationsDto allocationsDto)
{
...
catch (Exception ex)
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Json(new { success = false, responseText = ex.Message });
}
...
$.ajax({
type: "POST",
url: "/Allocation/UpdateAllocations",
data: JSON.stringify(allocationData),
contentType: "application/json; charset=utf-8",
dataType: "json"
})
.done(function (data) {
})
.fail(function (xhr, status, error) {
displayError("The ajax call to UpdateAllocations() action method failed:",
error, "Please see the system administrator.");
});
但是error参数是空的,status只有一个单词“error”以及xhr.statusText。如何返回我自己的自定义文本,在这种情况下为 ex.Message??
【问题讨论】:
-
@gaetanoM 谢谢你的建议。不幸的是,该解决方案不适用于 MVC Core,它返回 HttpStatusCodeResult。 MVC Core 使用 StatusCodeResult 代替,它的构造函数只接受一个参数,即状态码,并且没有错误消息...
-
我使用了 return StatusCode(404, new { Message = ex.Message });结果相同...
标签: jquery ajax asp.net-core-mvc