【问题标题】:ASP.Net Core Error JSONASP.Net 核心错误 JSON
【发布时间】:2016-09-06 15:44:07
【问题描述】:

我正在使用 ASP.NET Core。我正在创建一个基本的 webapi。 我想在出现问题时显示 JSON 错误。

打印屏幕显示我想要在我的屏幕上。 唯一的问题是它发送的状态码为 200。

catch (NullReferenceException e)
{
    return Json(NotFound(e.Message));
}

我可以通过这样做来解决它:

return NotFound(new JsonResult(e.Message) {StatusCode = 404);

但我不喜欢这样,因为现在您可以使用 NotFound 指定状态码 500。

有人能把我引向正确的方向吗?

真诚地, 布莱希特

【问题讨论】:

  • 第二段代码是正确的做法。您“可以”将 500 指定为状态码,但您为什么要控制 api。
  • 您不必在JsonResult 上设置StatusCodeNotFound 方法已经在这样做了。

标签: c# asp.net json asp.net-core asp.net-core-mvc


【解决方案1】:

你不能做类似return NotFound(e.Message);的事情

或者您可能有自己的错误文档格式并选择return NotFound(new ErrorDocument(e.message));

如果您必须返回 JsonResult,请执行以下操作:

return new JsonResult(YourObject) { StatusCode = (int)HttpStatusCode.NotFound };

现在您也可以完全控制响应格式和状态代码。如果需要,您甚至可以附加序列化程序设置。 :)

【讨论】:

  • 如果我返回 NotFound(e.Message);然后错误消息显示为纯文本,因为 e.Message 是一个普通的“字符串”。我检查 ModelState 的其他错误在 JSON 中。它喜欢有一致性。我现在创建了犯错误的类。我将单独发布我的新解决方案。谢谢你给我指路。我正忙着使用 NotFound()。它完全忘记了只使用'new JsonResult'作为返回
  • 我了解模型状态检查。如果你想更好地处理这件事,我建议你使用一个关于here 的异常过滤器。然后你所需要担心的就是抛出一个适当的异常,如果没有围绕主代码的全局 try-catch 块,你的控制器会看起来不错。只是一个想法。是的,错误一致性是一件好事。 :)
  • 感谢您发布该链接。我会检查的!祝你有美好的一天!
【解决方案2】:

EDIT: Found a much better solution here on stackoverflow.

感谢 Swagata Prateek 提醒我只使用 return new JsonResult()。我确实通过这种方式解决了我的问题。

public class Error
{
    public string Message { get; }
    public int StatusCode { get; }

    public Error(string message, HttpStatusCode statusCode)
    {
        Message = message;
        StatusCode = (int)statusCode;
    }
}    


[HttpGet("{id}")]
public IActionResult Get(int id)
{
    try
    {
       return Ok(_manager.GetPokemon(id));
    }
    catch (NullReferenceException e)
    {
       var error = new Error(e.Message, HttpStatusCode.NotFound);
       return new JsonResult(error) {StatusCode = error.StatusCode};
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-12
    • 2019-02-01
    • 2018-10-03
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    相关资源
    最近更新 更多