简体   繁体   English

为什么使用HttpContext的MVC 4会话助手不能工作,而HttpContextBase却不能呢?

[英]Why MVC 4 session helper using HttpContext work and HttpContextBase does not?

I implemented a session helper to save and retrieve session variables based on the following example: (I try to minimize the use of session variables) Stackoverflow question 我实现了一个会话的辅助来保存和检索基于以下示例会话变量:(我尝试使用会话变量的最小化) #1问题

I use MVC 4 and target .NET 4.5 on Visual Studio 2012. 我在Visual Studio 2012上使用MVC 4和目标.NET 4.5。

I implemented a setter. 我实现了一个二传手。 This one uses HttpContextBase (ie controller.HttpContext): 这一个使用HttpContextBase(即controller.HttpContext):

public class HttpContextBaseSessionHelper : ISessionHelper
{
    private readonly HttpContextBase _context;

    public HttpContextBaseSessionHelper(HttpContextBase context)
    {
        _context = context;
    }

    public T Get<T>(string key)
    {
        object value = _context.Session[key];
        return value == null ? default(T) : (T)value;
    }

    public void Set<T>(string key, T value)
    {
        _context.Session[key] = value;
    }
}

This implementation uses HttpContext (ie System.Web.HttpContext.Current): 此实现使用HttpContext(即System.Web.HttpContext.Current):

public class HttpContextSessionHelper : ISessionHelper
{
    private readonly HttpContext _context;

    public HttpContextSessionHelper(HttpContext context)
    {
        _context = context;
    }

    public T Get<T>(string key)
    {
        object value = _context.Session[key];
        return value == null ? default(T) : (T)value;
    }

    public void Set<T>(string key, T value)
    {
        _context.Session[key] = value;
    }
}

In the controller the HttpContext property is of type HttpContextBase (Controller.HttpContext). 在控制器中,HttpContext属性的类型为HttpContextBase(Controller.HttpContext)。 I can mock (using Moq) the ISessionHelper based on HttpContextBase. 我可以模拟(使用Moq)基于HttpContextBase的ISessionHelper。

I use the following two controller actions to see in the running app (not the unit test) if the correct values are set and retrieved: 我使用以下两个控制器操作来查看正在运行的应用程序(而不是单元测试)中是否设置和检索了正确的值:

public ActionResult SessionSet()
{
    _sessionHelper.Set<string>("TestKey", "TestValue");
    ViewBag.SessionValue = (string)HttpContext.Session["TestKey"];
    return View();
}

public ActionResult SessionGet()
{
    HttpContext.Session["TestKey"] = "TestValue";
    ViewBag.SessionValue = _sessionHelper.Get<string>("TestKey");
    return View();
}

This implementation throws a NullReference exception when using the above actions: 使用以上操作时,此实现将引发NullReference异常:

_sessionHelper = new HttpContextBaseSessionHelper(HttpContext);

But this implementation works just fine: 但是此实现工作正常:

_sessionHelper = new HttpContextSessionHelper(System.Web.HttpContext.Current);

My question is why does this happen? 我的问题是为什么会这样? Shouldn't the implementation using HttpContextBase work and the one using HttpContext give a problem seeing that Controller.HttpContext returns a HttpContextBase type? 看到Controller.HttpContext返回HttpContextBase类型,使用HttpContextBase的实现和使用HttpContext的实现是否会出现问题?

This implementation throws a NullReference exception when using the above actions: 使用以上操作时,此实现将引发NullReference异常:

_sessionHelper = new HttpContextBaseSessionHelper(HttpContext); _sessionHelper =新的HttpContextBaseSessionHelper(HttpContext);

You have placed this code in the constructor of your controller, haven't you? 您已将此代码放置在控制器的构造函数中,不是吗? That won't work because the HttpContext property is not yet initialized at this stage. 那是行不通的,因为在此阶段尚未初始化HttpContext属性。 You should put this code in the Initialize method if you want to access any HttpContext related properties: 如果要访问任何与HttpContext相关的属性,则应将此代码放在Initialize方法中:

protected override void Initialize(RequestContext requestContext)
{
    base.Initialize(requestContext);
    _sessionHelper = new HttpContextBaseSessionHelper(HttpContext);
}

Remark about the following sentence from your question: 关于您的问题中的以下句子进行评论:

I try to minimize the use of session variables 我尝试最小化会话变量的使用

You should not be trying to minimize the use of session variables. 您不应该尝试最小化会话变量的使用。 You should try to completely get rid of any ASP.NET Session from your application. 您应该尝试完全摆脱应用程序中的任何ASP.NET会话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpContextBase 不包含“WebSockets”MVC 的定义 - HttpContextBase does not contain a definition for 'WebSockets' MVC 带有静态变量的HttpContext.Current.Session绑定不起作用 - Binding to HttpContext.Current.Session w/ Static Variable Does Not Work 助手不起作用(ASP.NET MVC) - Helper does not work (ASP.NET MVC ) 如何在ASP.NET MVC 4中使用Autofac注入HttpContextBase - How to inject HttpContextBase using Autofac in ASP.NET MVC 4 Controller.HttpContext(HttpContextBase)线程安全吗? - Is Controller.HttpContext (HttpContextBase) thread safe? 无法将httpcontextbase传递给具有HttpContext类型变量的方法 - can not pass httpcontextbase into method with HttpContext type variable 在MVC3中使用Session的静态帮助程序阻止我进行单元测试 - Static helper using Session in MVC3 prevents me from unittesting 在单独的帮助程序 class 中访问 controller 之外的 HttpContext session 的最佳实践 - Best practice to access an HttpContext session outside the controller in a separate helper class HttpContext.Current.Session是否可以与负载均衡器一起使用? - Will HttpContext.Current.Session work with load balancer? 会话超时在asp.net mvc 4 C#中不起作用。 为什么? - Session timeout does not work at asp.net mvc 4 C# . Why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM