英文:
.Net core controller tempdata add/remove
问题
实现 ExceptionFilterAttribute 的 OnException 方法并需要重定向。
旧的实现(.Net 48)如下:
exceptionContext.Controller.TempData.Remove("");
exceptionContext.Controller.TempData.Add("");// 添加异常消息
exceptionContext.Controller.ControllerContext.HttpContext.Response.Redirect(url);
对于重定向,我想可以这样做:
exceptionContext.HttpContext.Response.Redirect(url);//这样正确吗?
请建议替代的 remove 和 add 方法。
英文:
Implementing ExceptionFilterAttribute OnException method and need to redirect
The old implementation (.Net 48) was
exceptionContext.Controller.TempData.Remove("");
exceptionContext.Controller.TempData.Add("");//exception message is added
exceptionContext.Controller.ControllerContext.HttpContext.Response.Redirect(url);
For the redirect I guess I can:
exceptionContext.HttpContext.Response.Redirect(url);//Is this correct?
Please suggest alternate for the remove and add?
答案1
得分: 1
在 .NET 6 中,如果您想在 ExceptionFilter 中访问 TempData,就没有 exceptionContext.Controller.TempData
。您可以尝试将 TempdataDictionaryFactory 注入到过滤器中。
例如,我尝试了以下方式:
public class MyExceptionFilter : ExceptionFilterAttribute
{
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public MyExceptionFilter(ITempDataDictionaryFactory tempDataDictionaryFactory)
{
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public override void OnException(ExceptionContext context)
{
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
tempData.Add("key", "value");
context.Result = new RedirectToActionResult("Error", "Home", null);
}
}
在 Program.cs 中:
builder.Services.AddControllersWithViews(x => x.Filters.Add(typeof(MyExceptionFilter)));
结果:
英文:
In .net 6,there's no exceptionContext.Controller.TempData
if you want to access TempData in your ExceptionFilter,you could try to inject the TempdataDictionaryFactory into the filter
For example, I tried as below:
public class MyExceptionFilter : ExceptionFilterAttribute
{
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public MyExceptionFilter(ITempDataDictionaryFactory tempDataDictionaryFactory)
{
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public override void OnException(ExceptionContext context)
{
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
tempData.Add("key", "value");
context.Result = new RedirectToActionResult("Error", "Home", null);
}
}
in Program.cs:
builder.Services.AddControllersWithViews(x=>x.Filters.Add(typeof(MyExceptionFilter)));
The Result:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论