首页 新闻 会员 周边 捐助

asp.net core 自定义错误页面中如何通过日志记录500错误时请求的url

0
悬赏园豆:50 [已解决问题] 解决于 2019-02-17 16:04

配置自定义错误页面的扩展方法如下:

public static class CustomErrorPagesExtensions
{
    public static IApplicationBuilder UseCustomErrorPages(this IApplicationBuilder app)
    {
        return app.UseExceptionHandler(new ExceptionHandlerOptions
        {
            ExceptionHandlingPath = "/errors/500",
            ExceptionHandler = app.New().UseMvcWithDefaultRoute().Build()
        }).UseStatusCodePagesWithReExecute("/errors/{0}");
    }
}

显示自定义错误页面的 MVC Action 代码如下:

public class ErrorsController : Controller
{
    [Route("errors/{statusCode:int}")]
    public IActionResult StatusCodePage(HttpStatusCode statusCode, [FromServices]ICompositeViewEngine compositeViewEngine)
    {
        var viewName = ((int)statusCode).ToString();
        bool viewExists = compositeViewEngine.FindView(ControllerContext, viewName, true).Success;
        var view = viewExists ? View(viewName) : View("Default", statusCode);
        view.StatusCode = (int)statusCode;
        return view;
    }
}

请问如何可以实现在发生500错误时在日志中记录对应的 url ?

dudu的主页 dudu | 高人七级 | 园豆:30925
提问于:2019-02-17 14:14
< >
分享
最佳答案
0

可以通过 IExceptionHandlerPathFeature 的 Path 属性获取请求的原始 url

if (statusCode == HttpStatusCode.InternalServerError)
{
    var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>() ;
    if (feature != null)
    {
        var logger = loggerFactory.CreateLogger<ErrorsController>();
        logger.LogError($"500 Internal Server Error: {feature.Path}");
    }
}
dudu | 高人七级 |园豆:30925 | 2019-02-17 16:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册