[英]How pass the TempData in ExceptionFilterAttribute in Asp.Net Core
I have tried to create the Exception filter
for my controller in Asp.Net Core MVC like this: 我试图像这样在Asp.Net Core MVC中为我的控制器创建
Exception filter
:
public class ControllerExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
public ControllerExceptionFilterAttribute(
IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public override void OnException(ExceptionContext context)
{
//How construct a temp data here which I want to pass to error page?
var result = new ViewResult
{
ViewName = "Error"
};
context.ExceptionHandled = true; // mark exception as handled
context.Result = result;
}
}
I need in OnException
method work with TempData
- how can I set some exception information to TempData
in this place? 我需要在
OnException
方法中与TempData
一起TempData
-如何在该位置为TempData
设置一些异常信息? I have used this TempData to some notification. 我已经将此TempData用于一些通知。
There is missing something like this: context.Controller.TempData["notification"]
- Controller property was probable removed. 缺少这样的内容:
context.Controller.TempData["notification"]
-控制器属性可能已删除。
You can achieve what you're looking for with the ITempDataDictionaryFactory
, which you can take into your constructor via dependency injection. 您可以使用
ITempDataDictionaryFactory
实现所需的ITempDataDictionaryFactory
,可以通过依赖注入将其纳入构造函数。 This has a single function, GetTempData
, which can be used for accessing what you refer to as TempData
. 它只有一个函数
GetTempData
,可用于访问您称为TempData
。 Here's a complete example to suit your needs: 这是一个满足您需求的完整示例:
public class ControllerExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public ControllerExceptionFilterAttribute(
IHostingEnvironment hostingEnvironment,
ITempDataDictionaryFactory tempDataDictionaryFactory)
{
_hostingEnvironment = hostingEnvironment;
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public override void OnException(ExceptionContext context)
{
//How construct a temp data here which I want to pass to error page?
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
var result = new ViewResult
{
ViewName = "Error"
};
context.ExceptionHandled = true; // mark exception as handled
context.Result = result;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.