如何在 Asp.Net Core 中传递 ExceptionFilterAttribute 中的 TempData

How pass the TempData in ExceptionFilterAttribute in Asp.Net Core

我尝试在 Asp.Net 核心 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"] - 控制器 属性 可能已被删除。

您可以使用 ITempDataDictionaryFactory, which you can take into your constructor via dependency injection. This has a single function, 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;
    }
}