配置自定义错误页面的扩展方法如下:
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 ?
可以通过 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}");
}
}