gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:08:30 25 4
gpt4 key购买 nike

我尝试在 Asp.Net Core MVC 中为我的 Controller 创建异常过滤器,如下所示:

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"] - Controller 属性可能已被删除。

最佳答案

您可以使用 ITempDataDictionaryFactory 实现您想要的效果,您可以通过依赖注入(inject)将其带入构造函数。这有一个功能,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;
}
}

关于c# - 如何在 Asp.Net Core 的 ExceptionFilterAttribute 中传递 TempData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47430646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com