如何在 .Net Core 中返回错误状态代码 401 的自定义错误消息?

Posted

技术标签:

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

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

【问题讨论】:

这能回答你的问题吗? How to return a specific status code and no contents from Controller? 整个 API 或特定操作都需要它吗? 【参考方案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();

【讨论】:

以上是关于如何在 .Net Core 中返回错误状态代码 401 的自定义错误消息?的主要内容,如果未能解决你的问题,请参考以下文章