【发布时间】:2020-09-02 11:25:14
【问题描述】:
.Net Core 3.1
我有一个 ExceptionFilter,我想通过 RedirectResult 传递 TempData 值。
下面是我的代码:
public class CustomExceptionFilterAttribute : IExceptionFilter
{
private readonly ITempDataProvider _tempDataProvider;
public CustomExceptionFilterAttribute(ITempDataProvider tempDataProvider)
{
_tempDataProvider = tempDataProvider;
}
public void OnException(ExceptionContext context)
{
//Log The Exception here
//After Log
var url = context.HttpContext.Request.Path.ToUriComponent();
context.ExceptionHandled = true;
context.HttpContext.Response.Clear();
var tempData = new TempDataDictionary(context.HttpContext, _tempDataProvider);
tempData.Add("UserFriendlyMessage", "An Error Occured! Please contact Admin!");
tempData.Keep("UserFriendlyMessage"); //This didn't work either...
var result = new RedirectResult(url);
context.Result = result;
}
}
[TypeFilter(typeof(CustomExceptionFilterAttribute))]
public class MyController : Controller
{...
public IActionResult MyAction()
{
return View();
}
[HttpPost]
public IActionResult MyAction(MyModel model)
{
try
{
int a = 5;
int b = a / 0;
}
catch(Exception ex)
{
}
return View();
}
正如您在上面看到的,我的目标是将用户重定向到同一页面(发生异常的地方)并防止他们重定向 500StatusCode 错误页面。
实际上这段代码以我想要的方式重定向用户,但只是 TempData 值没有通过。
我试过了:
- context.HttpContext.Response.Clear(); 试过这个代码,没有这个代码。
- tempData.Keep("UserFriendlyMessage"); 试过这个代码,没有这个代码。
【问题讨论】:
-
实现此目的的一种方法是使用 UseExceptionHandler 中间件在 ASP.NET Core 中实现全局异常处理程序。如果适合您,我可以提供完整的源代码吗?
-
@ChandanKumar 先生,我将不胜感激。
标签: .net asp.net-mvc asp.net-core .net-core error-handling