开发者

Strongly Type Session Variables in MVC 3

I am trying to set up a session wrapper in a MVC 3 application. This post gives the general idea of what I'd like to do: http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx

However the session is always null when it is accessed. This class is outside the controllers, and currently, the variable in question is being accessed outside the controllers.

Here is the class:

public sealed class SessionManager : IRequiresSessionState
{
    private const string CurrentCultureKey = "CurrentCulture";
    public sta开发者_StackOverflowtic 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;
        }
    }
}

I added the IRequiresSessionState, but that did not seem to work either.

I am using this variable to help with a custom routing, in the case I cannot have the culture in the address (/En/Controller/Action) I wanted to track it in the session. This would be helpful for custom error views.

I have a feeling I'm heading down a wrong road, so if anyone can point me in the right direction I would appreciate it.


So, in the end I did not find a way to access the session outside the controller action methods. I instead stored the value in a cookie, which made more sense.

However, if the user had cookies turned off, and an error happened on the site, currently they would be forwarded to the default language. I will likely have to store this information in the database, or a cache item with a unique ID in the case there are no cookies.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜