ASP.NET Core Web API 如何使用 try catch 方法捕获 401 和 403 错误
ASP.NET Core Web API how to catch the 401 and 403 errors using the try catch method
我正在使用库 Microsoft.AspNetCore.Http
和 Microsoft.AspNetCore.Mvc
。我也在使用 Identity 的 JWT 令牌。
当令牌过期时,API 抛出一个 http 401 错误,如果声明错误,它 returns 一个 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 });
}
}
您可以通过将以下内容添加到 Startup.cs
中的 Configure 方法来完成此操作
这将使您能够拦截和更改响应的各个方面以及内容类型。在下面的示例中,我们将返回一个带有消息的简单 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());
}
});
根据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;
}
});
我正在使用库 Microsoft.AspNetCore.Http
和 Microsoft.AspNetCore.Mvc
。我也在使用 Identity 的 JWT 令牌。
当令牌过期时,API 抛出一个 http 401 错误,如果声明错误,它 returns 一个 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 });
}
}
您可以通过将以下内容添加到 Startup.cs
中的 Configure 方法来完成此操作这将使您能够拦截和更改响应的各个方面以及内容类型。在下面的示例中,我们将返回一个带有消息的简单 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());
}
});
根据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;
}
});