我正在全球范围内处理asp.net核心中的未处理异常。下面的代码可以很好地处理异常情况。但是在出现404错误时无法登录。
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.2
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<ExceptionHandlerMiddleware>();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
}
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
try
{
await _next(httpContext);
if (httpContext.Response.StatusCode ==(int) HttpStatusCode.NotFound)
{
var feature = httpContext.Features.Get<IExceptionHandlerFeature>();
/// I am getting null here. I don't know why
//ExceptionManager.ProcessException(feature.Error);
}
}
catch (Exception ex)
{
ExceptionManager.ProcessException(ex);
httpContext.Response.Redirect("/Error");
}
}
}```
My expected result is log the exception into db and redirect to a static error html page whether it is 404 error Or it is unhanded exception.