加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – HttpContext.Items与ASP.NET MVC

发布时间:2020-12-15 19:05:34 所属栏目:asp.Net 来源:网络整理
导读:我正在使用我自己的ApplicationContext类,它使用单例模式。我想把它的实例存储在HttpContext.Items,因为它可以在请求的所有部分中访问。我一直在阅读关于使用HttpContext与ASP.NET MVC和其中一个主要的痛苦,它引入测试的复杂性。我试过研究HttpContext.It
我正在使用我自己的ApplicationContext类,它使用单例模式。我想把它的实例存储在HttpContext.Items,因为它可以在请求的所有部分中访问。我一直在阅读关于使用HttpContext与ASP.NET MVC和其中一个主要的痛苦,它引入测试的复杂性。我试过研究HttpContext.Items的可测试性,但所有我可以找到的东西在Session。我发现的唯一的东西是在Wrox( pdf link here)的专业ASP.NET 3.5 MVC书的一个示例章节。在第15页它说:

Something You Can’t Use: HttpContext.Items
Above in this section,we came clean and told you that we lied to you: HttpContext is not shared between ASP.NET MVC and ASP.NET Web Forms. As a result of this,you cannot use the HttpContext.Items collection to store and retrieve bits of data.

The reason for this is because once you redirect to a Controller,your HttpHandler becomes the System.Web.Mvc.MvcHandler,which is created using HttpContextWrapper,which will have its own definition of HttpContext.Current. Unfortunately,during this handshake,things like HttpContext.Items are not transferred.

What this boils down to is that the HttpContext types,despite looking and sounding very much the same,are not the same,and you cannot pass data in this way.

现在,我已经尝试测试这一点,据我所知,如果你重定向到另一个控制器使用RedirectToAction,HttpContext.Items确实保持。我使用默认的ASP.NET MVC项目来测试这个。我做的是,将此方法添加到Global.asax.cs:

protected void Application_BeginRequest()
{
    Context.Items["Test"] = "Hello World";
}

在HomeController.cs中,我已经将Index方法更改为:

public ActionResult Index()
{
    return RedirectToAction("About");
}

并将About方法更改为:

public ActionResult About()
{
    Response.Write(Convert.ToString(HttpContext.Items["Test"]));
    return View();
}

当我运行应用程序时,页面正确重定向到/ Home / About和Response.Writes在global.asax.cs中设置的正确的“Hello World”字符串。

所以,在我看来,似乎我不知道这本书是什么意思,当他们说
“HttpContext.Items之类的东西不会被传输”或者它传输这些东西,可以使用HttpContext.Items。

如果你们建议我避免HttpContext.Items,有没有另一种方法来存储一个对象跨请求在每个请求的基础上?

解决方法

你的问题是要几件事,但我认为项目#1是你要找的答案。

>是否可以使用Context.Items在每个请求的缓存?是。如果在进程中,每个请求,在Web场中的每台机器是您的标准,那么Context.Items给你。>是Context.Items难以测试吗?至于可测试性,我会隐藏Context.Items在某种类型的接口后面。这样,您可以获得单元测试功能,而无需直接引用Context.Items。否则,你需要测试什么Context.Items?框架将存储和检索值?保持你的代码不知道System.Web,你会是一个快乐的露营者。>将Context.Items生存RedirectToAction?否。您的测试无效。它在每个Web请求中设置“Hello,world”,您的测试跨两个Web请求。第一个是当调用Index操作时。第二个是当RedirectToAction操作被调用时(它是一个HTTP 302)。要使其失败,请在“索引”操作中设置一个新值,并查看它是否保留在“关于”操作中。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读