如何在 Asp.Net Core 的 JsonResult 中 return 错误状态?

How to return error status in JsonResult in Asp.Net Core?

我正在尝试 return 将 Asp.Net MVC 5 应用程序迁移到核心版本后的错误状态。

在我的旧应用程序中,我使用了从 JsonResult 继承的 class (JsonHttpStatusResult),如果有的话,return 会捕获错误。但是,当尝试将其添加到新项目时,不幸的是它不再具有某些功能。

我想对 Asp.Net 核心版本使用相同的概念,因为我 不想 return 真或假 如果JsonResult 中发生错误。以下是它在 MVC 5 中如何工作的示例:

CLASS:

public class JsonHttpStatusResult : JsonResult
{
    private readonly HttpStatusCode _httpStatus;

    public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
    {
        Data = data;
        _httpStatus = httpStatus;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
        base.ExecuteResult(context);
    }
}

示例 JSONRESULT:

public JsonResult Example()
{
    try
    {
        //Some code
        return Json(/*something*/);
    }
    catch (Exception ex)
    {
        return new JsonHttpStatusResult(ex.Message, HttpStatusCode.InternalServerError);
    }
}

AJAX 请求:

$.ajax({
    url: "/Something/Example",
    type: "POST",
    dataType: "json",
    success: function (response) {
        //do something
    },
    error: function (xhr, ajaxOptions, thrownError) {
         //Show error
    }
});

如何在 Asp.Net Core 中执行此操作或类似操作?

您不必在 ASP.NET Core 中创建自己的实现。

ASP.NET Core 为 JsonResult class.

引入了 new StatusCode Property

所以只需将您的代码更改为:

catch (Exception ex)
{
    return new JsonResult(ex.Message){
        StatusCode = (int)HttpStatusCode.InternalServerError
    };
}