我已经在 ASP.NET MVC Core 中看到了多种捕获异常的方法,但我需要了解为什么我所做的没有按预期工作。
我添加了以下内容:
public abstract class GenericActionFilter : ActionFilterAttribute
{
protected readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (await OnBeforeActionExecutionAsync(context))
{
var executed = await next();
if (executed.Exception != null && !executed.ExceptionHandled)
{
await OnExceptionAsync(context, executed.Exception);
}
else
{
await OnAfterActionExecutionAsync(context);
}
}
}
public virtual Task<bool> OnBeforeActionExecutionAsync(ActionExecutingContext context)
{
return Task.FromResult(true);
}
public virtual Task OnAfterActionExecutionAsync(ActionExecutingContext context)
{
return Task.CompletedTask;
}
public virtual Task OnExceptionAsync(ActionExecutingContext context, Exception ex)
{
return Task.CompletedTask;
}
}
并像这样使用它:
public class ExceptionFilter : GenericActionFilter
{
public IntegrationScenarioSettings Settings { get; set; }
public override Task OnExceptionAsync(ActionExecutingContext context, Exception ex)
{
context.Result = new ContentResult
{
Content = Settings.ApiExecutionExceptionMessage,
StatusCode = (int)HttpStatusCode.ServiceUnavailable
};
//outputs to endpoint.log
Logger.Error(ex);
return Task.CompletedTask;
}
}
动作中的底层代码抛出异常,而不是看到 503,我仍然是 500。
我在这里缺少什么?
米琪卡哇伊
相关分类