英文:
Redirect StatusCode with message to Error Page
问题
最近发现了一个奇怪的行为。当我使用带有消息的状态代码时,无法重定向到默认错误消息。
我正在使用.Net Core(Net 7.0)
program.cs
HomeController.cs
输出
目标是重定向到这个页面:
任何想法都将不胜感激。谢谢。
英文:
Recently found a strange behavior. I am not able to redirect to default error message when I use a status code with a message.
I am using .Net Core (Net 7.0)
The goal is a redirect to this page:
Any ideas will appreciated. Thank you.
答案1
得分: 1
我按照你提到的方式尝试了一下,发现如果返回带有错误消息的 ObjectResult,它不会触发错误处理程序,处理程序只处理 NotFoundResult 和 StatusCodeResult。
例如,如果我尝试使用 return StatusCode(500);
,它可以命中 "/Home/Error"
,使用中间件 app.UseStatusCodePagesWithReExecute("/Home/Error");
尝试直接抛出带有消息的异常,然后在错误控制器中尝试以下方式:
var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
var errmessage = exceptionHandlerPathFeature?.Error.Message;
var vm = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorMessage = errmessage };
return View(vm);
结果:
英文:
I tried as you mentioned and found that if you return an ObjectResult with ErrorMessage,it won't trigger the error handler,The handler only handle NotFoundResult\StatueCodeResult....
For example,if I try with return StatusCode(500);
it could hit"/Home/Error"
with the middleware app.UseStatusCodePagesWithReExecute("/Home/Error");
Try throw an Excption with message directly
and try as below in Error Controller:
var exceptionHandlerPathFeature =HttpContext.Features.Get<IExceptionHandlerPathFeature>();
var errmessage = exceptionHandlerPathFeature?.Error.Message;
var vm = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorMessage = errmessage };
return View(vm);
Result:
答案2
得分: 0
UseExceptionHandler中间件用于捕捉异常,记录它并重新执行它,使用给定的路径。重新执行将会触发HomeController的Error方法,并从Views的共享文件夹返回Error视图。
根据您代码的第22行,您正在返回StatusCodeResult,这不是任何异常。使用UseExceptionHandler的思路是捕捉错误。
要在状态码上重定向到特定页面,您可以使用UseStatusCodePages中间件。
您可以执行以下操作:
-
添加中间件(在UseHttpRedirection之后添加)
-
在HomeController中添加相关的操作方法
-
在共享文件夹或主文件夹中添加视图。
英文:
UseExceptionHandler middleware is use to catch exception, log it and re-execute it with given path. Re-execution will hit the HomeController's Error method and it will return the Error view from shared folder of Views.
From your code on line no 22 you are returning StatusCodeResult and it is not any exception. Idea is UseExceptionHandler is use to catch error.
To redirect to particular page on status code, you can use UseStatusCodePages middleware.
You can do following:
- Add middleware (Add after UseHttpRedirection)
- Add related action method in HomeController
- Add views in shared or home folder.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论