【问题标题】:Asp.Net Core MVC capture application exception detailsAsp.Net Core MVC 捕获应用程序异常详情
【发布时间】:2017-04-24 07:56:11
【问题描述】:

经过一些研究,我找不到在 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);
      }
    });
 }
);

我只需要捕获错误详细信息,不覆盖默认行为(相当默认的错误页面等)。我不需要任何自定义异常处理程序,实际上我只需要抓取异常。我想在应用程序级别执行此操作,因此实现 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);
    }
}

这是我想保留的页面:

【问题讨论】:

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


    【解决方案1】:

    解决方案是将 Elm 用于 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。编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 2014-12-04
      • 2015-09-25
      • 1970-01-01
      相关资源
      最近更新 更多