[英]ASP.NET Core - handling 404 and 500 error
I try to handle 404 and 500 error in ASP.NET MVC 6. 我尝试在ASP.NET MVC 6中处理404和500错误。
I have Action in controller which render page with error status and description: 我在控制器中有Action,它呈现具有错误状态和描述的页面:
[HttpGet] [Route("/Errors/{status}")] public IActionResult Errors(int status) { var model = Mapper.Map<ErrorViewModel>(BaseData); model.ErrorCode = status; if (error_descriptions.ContainsKey(status)) model.Description = error_descriptions[status]; else model.Description = "Неизвестная ошибка"; return View(model); }
I enable status code pages and exception handler: 我启用状态代码页和异常处理程序:
app.UseExceptionHandler("/Errors/500"); app.UseExceptionHandler( “/错误/ 500”); app.UseStatusCodePagesWithReExecute("/Errors/{0}");
app.UseStatusCodePagesWithReExecute( “/错误/ {0}”);
I want to ger 404
error when url doesn't match any route and when queryes to Database return empty sequencies (access to nonexists elements). 当url与任何路由不匹配时,我想要ger
404
错误,当查询到数据库时返回空序列(访问nonexists元素)。
I've got InvalidOperationException
when LINQ return empty sequence ( the sequence contains no elements
). 当LINQ返回空序列时(
the sequence contains no elements
),我有InvalidOperationException
。 I want to handle global exception, show 404
in this case and 500
in other. 我想处理全局异常,在这种情况下显示
404
,在其他情况下显示500
。
I make a simple filter and check Exception in OnException
: 我创建一个简单的过滤器并检查
OnException
异常:
public void OnException(ExceptionContext context) { logger.LogError(context.Exception.Message); if (context.Exception is System.InvalidOperationException) ; //NEED TO CALL HomeController.Error(404) }
It works, but I don't know how to call my action and show error page 它有效,但我不知道如何调用我的动作并显示错误页面
You can create a model in the OnException
method like 您可以在
OnException
方法中创建模型,如
public void OnException(ExceptionContext context)
{
var model = new HandleErrorInfo(filterContext.Exception, "YourError Controller","Errors");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.