英文:
Handle Errors on Asp.net core6 mvc
问题
I am studying asp.net core and I need to fix error handling problems.
我正在学习 asp.net core,需要解决错误处理问题。
I have some questions about them
我有一些关于这个问题的问题。
1- should we catch all error types and return specific views each of them? 400 401 403 404 500 and more
1- 我们是否应该捕获所有错误类型,并针对每种错误返回特定的视图?例如 400、401、403、404、500 等等。
2-if yes, which method is the best practice? Middleware or filters or any other? Can you share some samples please?
2- 如果是的话,哪种方法是最佳实践?中间件、过滤器还是其他方法?你能分享一些示例吗?
3-if no, what kind of route should I follow for errors ?
3- 如果不是的话,我应该采取什么样的路线来处理错误?
英文:
I am studying asp.net core and I need to fix error handling problems.
I have some questions about them
1- should we catch all error types and return specific views each of them? 400 401 403 404 500 and more
2-if yes, which method is the best practice? Middleware or filters or any other? Can you share some samples please?
3-if no, what kind of route should I follow for errors ?
答案1
得分: 0
你可以获取所有的响应代码,是否需要为每个代码显示不同的页面由你决定。
例如,使用 UseStatusCodePagesWithReExecute
中间件:
Program.cs:
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
Controller:
public IActionResult Error(int? statusCode = null)
{
if (statusCode.HasValue)
{
ViewData["Message"] = statusCode;
return View("ErrorPage");
}
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[Route("ErrorPage")]
public IActionResult ErrorPage()
{
return View();
}
在 ErrorPage.cshtml 中,你可以使用 ViewData["Message"]
获取响应代码并显示不同的内容。
或者你可以为每个响应代码创建一个视图,就像这样。
有关更多详细信息,你可以参考这个文档。
英文:
You can get all the response codes, it's up to you whether you need to display a different page for each code.
For example, use UseStatusCodePagesWithReExecute
middleware:
Program.cs:
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
Controller:
public IActionResult Error(int? statusCode = null)
{
if (statusCode.HasValue)
{
ViewData["Message"] = statusCode;
return View("ErrorPage");
}
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[Route("ErrorPage")]
public IActionResult ErrorPage()
{
return View();
}
In ErrorPage.cshtml, you can use ViewData["Message"]
to get the response code and display different content for it.
Or you can create a view for each response code like this.
For more details, you can refer to this document.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论