如何解决NET Core 3中没有路由匹配时,如何返回带有响应主体的404?
我有一个.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可以做到这一点吗?
解决方法
在.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核心中的错误进行了很好的解释。
参考
-
这是一个不错的博客,它解释了异常处理。您可以使用一些默认的中间件。
-
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1
-
https://medium.com/@matteocontrini/consistent-error-responses-in-asp-net-core-web-apis-bb70b435d1f8
使用.NET Core的IActionResult,您可以像这样返回新的NotFoundObjectResult
:
public IActionResult MyMethod()
{
var data = new {hello = "World"};
return new NotFoundObjectResult(data);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。