app.UseErrorHandler()可以访问错误详细信息吗?

时间:2015-05-21 22:13:58

标签: asp.net-core asp.net-core-mvc

在我的MVC4应用程序中,我有一个global {asax.cs覆盖Application_Error(object sender, EventArgs e),我可以提取exceptionstatusCoderequestedUrl(用于处理404)。这将被发送到我的控制器,错误页面将是不同的404s与5xx(这些获得堆​​栈跟踪)。我没有看到如何使用UseErrorHandler()将相同的信息添加到我的错误操作中。我在ASP.NET Core中使用正确的方法吗?

3 个答案:

答案 0 :(得分:14)

八月2016年第2期 - 更新1.0.0

<强> Startup.cs

using Microsoft.AspNet.Builder;

namespace NS
{
    public class Startup
    {
         ...
         public virtual void Configure(IApplicationBuilder app)
         {
             ...
             app.UseExceptionHandler("/Home/Error");
             ...
         }
     }
}

<强> HomeController.cs

using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;

namespace NS.Controllers
{
    public class HomeController : Controller
    {
        static ILogger _logger;
        public HomeController(ILoggerFactory factory)
        {
            if (_logger == null)
                _logger = factory.Create("Unhandled Error");
        }

        public IActionResult Error()
        {
            var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
            var error = feature?.Error;
            _logger.LogError("Oops!", error);
            return View("~/Views/Shared/Error.cshtml", error);
        }
    }
}

<强> project.json

...
"dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0",
     ...
}
...

答案 1 :(得分:4)

在Beta8中,来自火星的agua&#39;答案有点不同。

而不是:

var feature = Context.GetFeature<IErrorHandlerFeature>();

使用:

var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();

这还需要引用Microsoft.AspNet.Http.Features,以及Startup.cs中Configure()中的以下行:

app.UseExceptionHandler("/Home/Error");

答案 2 :(得分:1)

根据您配置的错误处理操作,您可以执行以下操作:

public IActionResult Error()
{
    // 'Context' here is of type HttpContext
    var feature = Context.GetFeature<IErrorHandlerFeature>();
    if(feature != null)
    {
        var exception = feature.Error;
    }
......
.......
相关问题