HttpContext.Items with ASP.NET MVC

旧城冷巷雨未停 提交于 2019-11-27 21:03:05
Nick Swarr

Your question is asking a few things but I think item #1 is the answer you're looking for.

  1. Is it fine to use Context.Items for caching on a per request basis? Yes. If in process, per request, per machine in the web farm is your criteria then Context.Items gives you that.

  2. Is Context.Items difficult to test with? As far as testability, I would hide Context.Items behind an interface of some sort. This way you get unit testing capabilities without having to reference Context.Items directly. Otherwise, what do you need to test about Context.Items? That the framework will store and retrieve values? Keep your code ignorant of System.Web and you'll be a happy camper.

  3. Will Context.Items survive RedirectToAction? No. Your test is invalid. It's setting "Hello, world" on every web request and your test spans two web requests. The first is when the Index action is called. The second is when RedirectToAction action is called (it's an HTTP 302). To make it fail, set a new value in the Index action and see if it's retained in the About action.

Use the TempData Dictionary, it is mainly for storing objects between Actions redirects:

public ActionResult Index()
{
    TempData.Add("Test", "Hello world");
    return RedirectToAction("About");
}

public ActionResult About()
{
    ViewData["Test"] = TempData["Test"];
    return View();
}

Then retrieve the value in your view:

<%=ViewData["Test"] %>

I did a test and TempData does, indeed, explode with session state disabled. My only advice would be to not store the object itself in temp data but store the simple typed fields as has been suggested. Since you're not serializing object trees it shouldn't be that big of a performance impact running out-of-process.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!