我试图在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;
}
}
我需要在OnException
方法中使用TempData
- 如何在此处为TempData
设置一些异常信息?我已将此TempData用于某些通知。
缺少类似这样的内容:context.Controller.TempData["notification"]
- 可能删除了控制器属性。
答案 0 :(得分:1)
您可以使用ITempDataDictionaryFactory
实现您正在寻找的内容,您可以通过依赖注入将其带入构造函数中。这有一个函数GetTempData
,可用于访问您所指的TempData
。以下是满足您需求的完整示例:
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;
}
}