强烈键入MVC 3中的会话变量

时间:2011-06-25 00:26:49

标签: asp.net-mvc session variables

我正在尝试在MVC 3应用程序中设置会话包装器。这篇文章给出了我想做的一般概念:http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx

但是访问时,会话始终为null。这个类在控制器之外,目前,有问题的变量正在控制器外部访问。

这是班级:

public sealed class SessionManager : IRequiresSessionState
{
    private const string CurrentCultureKey = "CurrentCulture";
    public static Culture CurrentCulture
    {
        get
        {
            if (null != HttpContext.Current.Session[CurrentCultureKey])
                return (Culture)HttpContext.Current.Session[CurrentCultureKey];

            return Culture.En;
        }
        set
        {
            if (HttpContext.Current.Session != null)
            HttpContext.Current.Session[CurrentCultureKey] = value;
        }
    }
}

我添加了IRequiresSessionState,但这似乎也没有用。

我正在使用此变量来帮助自定义路由,如果我在地址中没有文化(/ En / Controller / Action),我想在会话中跟踪它。这对自定义错误视图很有帮助。

我有一种感觉,我正在走错路,所以如果有人能指出我正确的方向,我会很感激。

1 个答案:

答案 0 :(得分:0)

所以,最后我没有找到一种方法来访问控制器动作方法之外的会话。我改为将值存储在cookie中,这更有意义。

但是,如果用户关闭了Cookie并且网站上发生了错误,则目前他们将转发为默认语言。我可能必须将此信息存储在数据库中,或者在没有cookie的情况下将具有唯一ID的缓存项存储。