【问题标题】:How can I return a 404 with a response body when no route matches in NET Core 3?当 NET Core 3 中没有路由匹配时,如何返回带有响应正文的 404?
【发布时间】:2020-12-21 12:18:04
【问题描述】:

我有一个 .NET Core 3 API,我想在给定请求找不到匹配项时返回一个带有 ResponseBody 的 404。

如果 URL 错误,我想在 404 的正文中返回以下内容:

{
    "errorCode":  "678",
    "message": "resource inexistent"
}

开箱即用的行为是返回没有正文的 404。我需要在 ResponseBody 上发送有关错误的信息以进行故障排除。

我在这里看到使用 WebAPI 非常容易。 https://weblogs.asp.net/imranbaloch/handling-http-404-error-in-asp-net-web-api

NET Core 有办法解决这个问题吗?

【问题讨论】:

  • 您可以使用自定义错误中间件拦截错误,从那里您可以返回您想要的任何内容

标签: c# api .net-core routes backend


【解决方案1】:

在 .Net 核心中,您可以使用中间件来重写您的响应。

您可以内置 UseStatusCodes 中间件,当您使用此中间件时,它会触发 400 - 599 的状态码,您可以使用此中间件自定义您的响应。下面是一个示例代码,我将状态码 404 更改为 500 并返回带有自定义正文的响应。

app.UseStatusCodePages(async context =>
            {
                if (context.HttpContext.Response.StatusCode == 404)
                {
                    var noContentResponse = new NoContentResponse
                    {
                        errorCode = "678",
                        message = "resource inexistent"
                    };
                    var responeString = Newtonsoft.Json.JsonConvert.SerializeObject(noContentResponse);
                    var requestContent = new StringContent(responeString);
                    requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    context.HttpContext.Response.Body = await requestContent.ReadAsStreamAsync();
                    context.HttpContext.Response.StatusCode = 500;
                }
            });

您可以使用中间件做更多事情,请查看下面的博客,这些博客对处理 .net core 中的错误有很好的解释。

参考

【讨论】:

    【解决方案2】:

    使用 .NET Core 的 IActionResult,您可以像这样返回一个新的NotFoundObjectResult

    public IActionResult MyMethod() 
    {
        var data = new {hello = "World"};
        return new NotFoundObjectResult(data);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 2015-04-27
      • 2021-01-16
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      相关资源
      最近更新 更多