如何在.Net Core中为错误状态代码401返回自定义错误消息? [英] How can I return custom error message for error status code 401 in .Net Core?
本文介绍了如何在.Net Core中为错误状态代码401返回自定义错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮助我显示.Net Core WebApi中错误状态代码401的自定义错误消息.
Please help me to display a custom error message for an error status code 401 in .Net Core WebApi.
推荐答案
ASP Core文档介绍了如何处理自定义错误响应:
The ASP Core documentation explains how to handle custom error responses:
在您的情况下,可以在启动 Configure
方法中尝试添加 app.UseStatusCodePages
(添加对 Microsoft.AspNetCore.Http
的引用)
In your case, you could try app.UseStatusCodePages
in your startup Configure
method(add a reference to Microsoft.AspNetCore.Http
)
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseStatusCodePages(async context =>
{
if (context.HttpContext.Response.StatusCode == 401)
{
await context.HttpContext.Response.WriteAsync("Custom Unauthorized request");
}
});
//other middlewars
动作:
[HttpGet]
public ActionResult Get()
{
return Unauthorized();
}
这篇关于如何在.Net Core中为错误状态代码401返回自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文