0

经过一番研究,我找不到一种方法来捕获asp.net核心mvc中的应用程序异常并保留默认错误页面行为。实际上有两种自定义处理应用程序错误的方法。首先简单的方法是在Startup.cs文件中配置app.UseExceptionHandler("/Home/Error");这个,但是这样我就失去了默认的开发错误页面漂亮视图。其他的解决方案,以定制错误在asp.net mvc的核心是定义异常处理程序内嵌处理,但是这将导致默认的错误页面覆盖,以及:Asp.Net核心MVC捕获应用程序异常详细信息

app.UseExceptionHandler(
options => { 
    options.Run(
    async context => 
    { 
     context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 
     context.Response.ContentType = "text/html"; 
     var ex = context.Features.Get<IExceptionHandlerFeature>(); 
     if (ex != null) 
     { 
     var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace }"; 
     await context.Response.WriteAsync(err).ConfigureAwait(false); 
     } 
    }); 
} 
); 

我只需要捕获错误的详细信息,没有覆盖默认行为(漂亮的默认错误页面,等等)。我不需要任何自定义异常处理程序,实际上我只需要抓取异常。我想在应用程序级别执行此操作,因此实施IExceptionFilter的自定义ExceptionHandlerAttribute将不起作用。该解决方案将删除默认错误页面,也需要捕获中间件错误,而不仅仅是控制器异常。下面的方法是不适用:

public class CustomExceptionFilter : IExceptionFilter 
{ 
    public void OnException(ExceptionContext context) 
    { 
     HttpStatusCode status = HttpStatusCode.InternalServerError; 
     String message = String.Empty; 

     var exceptionType = context.Exception.GetType(); 
     if (exceptionType == typeof(UnauthorizedAccessException)) 
     { 
      message = "Unauthorized Access"; 
      status = HttpStatusCode.Unauthorized; 
     } 
     else if (exceptionType == typeof(NotImplementedException)) 
     { 
      message = "A server error occurred."; 
      status = HttpStatusCode.NotImplemented; 
     } 
     else if (exceptionType == typeof(MyAppException)) 
     { 
      message = context.Exception.ToString(); 
      status = HttpStatusCode.InternalServerError; 
     } 
     else 
     { 
      message = context.Exception.Message; 
      status = HttpStatusCode.NotFound; 
     } 
     HttpResponse response = context.HttpContext.Response; 
     response.StatusCode = (int)status; 
     response.ContentType = "application/json"; 
     var err = message + " " + context.Exception.StackTrace; 
     response.WriteAsync(err); 
    } 
} 

这页,我想继续: default error page pretty view

回答