我正在寻找有关如何最好地处理asp net core异常的一些指导。基于微软的these文档,我设置了UseStatusCodePagesWithRedirects中间件。这适用于像404这样的东西。但是,对于我的代码中返回异常的API请求,这不起作用。因此,关注this doc我设置了一个例外过滤器。这种方式有效,这是我寻求帮助的地方。
我在类库中有以下代码,因此可以在别处重复使用。我api的迷你包装。我使用Flurl构建请求。我的viewModelBuilder调用GetAll。
public async Task<List<TableDto>> GetAll(int branchId)
{
var result = await _baseUrl.AppendPathSegment("/v1/Table/GetAll").WithOAuthBearerToken(await _authenticationManager.GetToken()).GetJsonAsync<List<TableDto>>();
return result;
}
如果GetAll抛出异常,则会发挥以下异常过滤器的作用。
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
// ex.Call.Response.StatusCode // This works with the original exception but not here
if (context.HttpContext.Response.StatusCode == (int)HttpStatusCode.Forbidden)
{
// Always 200
}
}
}
我想基于异常状态代码做不同的事情。因此,对于401或404,我想显示访问被拒绝的屏幕或登录屏幕,然后对于其他错误可能只是一般错误屏幕。但context.HttpContext.Response.StatusCode始终为200.
我知道如果我试着抓住原来的GetAll,如下所示
try
{
var result = await _baseUrl.AppendPathSegment("/v1/Table/GetAll").WithOAuthBearerToken(await _authenticationManager.GetToken()).GetJsonAsync<List<TableDto>>();
return result;
}
catch (FlurlHttpException ex)
{
if (ex.Call.Response != null)
{
if (ex.Call.Response.StatusCode == HttpStatusCode.Forbidden)
{
throw new ForbiddenException();
}
}
}
然后在异常过滤器中我可以执行以下操作
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
if (context.Exception is ForbiddenException)
{
}
}
}
然后我可以针对特定异常执行特定的操作,但是事情意味着我必须尝试捕获每个调用并使全局异常过滤器的点无效。任何建议将不胜感激。
由于 中号
修改
根据this的答案,我可以编写一个自定义中间件,我很快就做到了,但我仍然遇到了无法检查401或403并且只能够访问已抛出的自定义异常。如果我可以访问状态代码,那么我认为两种解决方案都可以正常工作