在自定义中间件中访问TempData [英] Access TempData within custom middleware

查看:110
本文介绍了在自定义中间件中访问TempData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有提供全局错误处理的自定义中间件.如果发现异常,则应使用参考号记录详细信息.然后,我想将用户重定向到错误页面,仅显示参考号.我的研究表明,TempData应该是理想的选择,但似乎只能从控制器上下文中进行访问.我尝试将参考号添加到HttpContext.Items["ReferenceNumber"] = Guid.NewGuid(); 但是此值会通过重定向丢失.

I have custom middleware that provides global error handling. If an exception is caught it should log the details with a reference number. I then want to redirect the user to an error page and only show the reference number. My research shows that TempData should be ideal for this but it only seems to be accessible from within a controller context. I tried adding the reference number to HttpContext.Items["ReferenceNumber"] = Guid.NewGuid(); But this value is lost through the redirect.

中间件如何通过重定向传递信息?我是否只需要将数字放在查询字符串中?

How can middleware pass information through a redirect? Do I just have to put the number in a querystring?

推荐答案

在中间件类中,您需要添加引用以访问所需的接口.我在单独的项目中拥有此中间件,并且需要添加此NuGet程序包.

Inside the middleware class you need to add a reference to get access to the required interfaces. I have this middleware in a separate project and needed to add this NuGet package.

using Microsoft.AspNetCore.Mvc.ViewFeatures;

然后,您可以在中间件中请求正确的服务.

This then allows you to request the correct services within the middleware.

//get TempData handle
ITempDataDictionaryFactory factory = httpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
ITempDataDictionary tempData = factory.GetTempData(httpContext);

拥有ITempDataDictionary之后,就可以像在控制器内使用TempData一样使用它.

After you have ITempDataDictionary you can use it like you would use TempData within a controller.

//pass reference number to error controller
Guid ReferenceNum = Guid.NewGuid();
tempData["ReferenceNumber"] = ReferenceNum.ToString();

//log error details
logger.LogError(eventID, exception, ReferenceNum.ToString() + " - " + exception.Message);

现在,当我在重定向后获得控制器时,我可以毫无疑问地拔出参考号并在我的视图中使用它.

Now when I get the the controller after a redirect I have no issues pulling out the reference number and using it in my view.

//read value in controller
string refNum = TempData["ReferenceNumber"] as string;
if (!string.IsNullOrEmpty(refNum))
    ViewBag.ReferenceNumber = refNum;

@*display reference number if one was provided*@
@if (ViewBag.ReferenceNumber != null){<p>Reference Number: @ViewBag.ReferenceNumber</p>}

将所有内容放在一起后,便会为用户提供参考号,他们可以为您提供参考号,以帮助您解决问题.但是,您并没有传递可能会被滥用的潜在敏感错误信息.

Once you put this all together, you give users a reference number that they can give you to help troubleshoot the problem. But, you are not passing back potentially sensitive error information which could be misused.

这篇关于在自定义中间件中访问TempData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆