【问题标题】:ASP.NET Core Web API how to catch the 401 and 403 errors using the try catch methodASP.NET Core Web API 如何使用 try catch 方法捕获 401 和 403 错误
【发布时间】:2021-12-03 09:26:36
【问题描述】:

我正在使用库 Microsoft.AspNetCore.HttpMicrosoft.AspNetCore.Mvc。我也在使用 Identity 的 JWT 令牌。

令牌过期后,API 会抛出 http 401 错误,如果声明错误,则返回 http 403 错误。

我需要能够捕捉这两个雕像并将它们包装成我统一的错误消息格式

public class ErrorMessage
{
     public int httpStatus { get; set; }
     public string Header { get; set; } = "Error";
     public string Message { get; set; }
}

我的标准 API 格式

[Authorize]
[HttpPost]
[Route("Logout")]
public async Task<IActionResult> Logout()
{
    try
    {
        ....
    }
    catch (Exception e)
    {
        _logger.LogError($"Error in {nameof(Login)}: {e}");
        return BadRequest(new ErrorMessage { httpStatus = 500, Message = e.Message });
    }
}

【问题讨论】:

标签: c# asp.net-core asp.net-core-webapi


【解决方案1】:

根据Handle errors in ASP.NET Core,你可以使用UseStatusCodePages

app.UseStatusCodePages(async statusCodeContext =>
{
    switch (statusCodeContext.HttpContext.Response.StatusCode)
    {
        case 401:
            statusCodeContext.HttpContext.Response.StatusCode = 400;
            await statusCodeContext.HttpContext.Response.WriteAsJsonAsync(new ErrorMessage { httpStatus = 500, Message = "some message" });
            break;
        case 403:
            statusCodeContext.HttpContext.Response.StatusCode = 400;
            await statusCodeContext.HttpContext.Response.WriteAsJsonAsync(new ErrorMessage { httpStatus = 500, Message = "some message" });
            break;
    }
});

【讨论】:

  • 天哪,这太完美了。谢谢你
【解决方案2】:

您可以通过将以下内容添加到 Startup.cs 中的 Configure 方法来完成此操作

这将让您拦截和更改响应的各个方面以及内容类型。在下面的示例中,我们返回一个带有 Message 的简单 JSON 对象。

app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized) // 401
    {
        context.Response.ContentType = "application/json";


        await context.Response.WriteAsync(new { 
            Message = "You must be logged in to access this resource."
        }.ToString());
    }

    if (context.Response.StatusCode == (int)HttpStatusCode.Forbidden) // 403
    {
        context.Response.ContentType = "application/json";

        await context.Response.WriteAsync(new
        {
            Message = "Your claims are incorrect."
        }.ToString());
    }
});

【讨论】:

  • 感谢您的回复。它给出了以下输出:无法解析 JSON。原始结果:Skylink.DAL.Models.StandardModels.ErrorMessage
  • 如何删除“无法解析 JSON”部分?
猜你喜欢
  • 2013-07-18
  • 2018-12-02
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
相关资源
最近更新 更多