【问题标题】:How can I return custom error message for error status code 401 in .Net Core?如何在 .Net Core 中返回错误状态代码 401 的自定义错误消息?
【发布时间】:2020-05-29 22:07:14
【问题描述】:

请帮助我在 .Net Core WebApi 中显示错误状态代码 401 的自定义错误消息。

【问题讨论】:

标签: asp.net-core asp.net-core-webapi asp.net-core-2.1


【解决方案1】:

ASP Core 文档解释了如何处理自定义错误响应:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1#usestatuscodepages

在你的情况下,你可以在你的启动Configure方法中尝试app.UseStatusCodePages(添加对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();
}

【讨论】:

    猜你喜欢
    • 2023-01-05
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多