Asp.Net Core MVC捕获应用程序异常详细信息

时间:2016-12-08 22:50:45

标签: exception-handling asp.net-core-mvc asp.net-core-1.0 asp.net-core-middleware

经过一些研究后,我无法找到一种方法来捕获asp.net core mvc中的应用程序异常并保留默认的错误页面行为。实际上有两种自定义处理应用程序错误的方法。首先,简单的方法是在Startup.cs文件中配置app.UseExceptionHandler("/Home/Error");这个,但这样我就丢失了默认的开发错误页面。在asp.net core 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);
      }
    });
 }
);

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

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

1 个答案:

答案 0 :(得分:0)

解决方案是使用Elm for ASP.NET Core应用程序,示例代码由Microsoft在其GitHub帐户上提供:https://github.com/aspnet/Diagnostics,还有经过重新设计,稳定版本的ASP.NET Core MVC记录器,在我的文章https://www.codeproject.com/Articles/1164750/Error-logging-in-ASP-NET-Core-MVC-Elmah-for-Net-Co中描述。快乐的编码!