What is an acceptable template for implementing Session in ASP.NET MVC sites?

Obviously, the typical WebForms approach will not work. How to track user in MVC world?

+5
source share
2 answers

The session works exactly the same as in Webforms. If you want to store simple information, use a form authentication cookie. If you want to save the contents of a shopping cart, a session is the place to go. I wrote a blog post about using a session with ASP.NET :

Suppose we want to save the whole variable in Session. We will create a wrapper around the Session variable, which will make it more pleasant:

:

public interface ISessionWrapper
{
    int SomeInteger { get; set; }
}

HttpContext:

public class HttpContextSessionWrapper : ISessionWrapper
{
    private T GetFromSession<T>(string key)
    {
        return (T) HttpContext.Current.Session[key];
    }

    private void SetInSession(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    public int SomeInteger
    {
        get { return GetFromSession<int>("SomeInteger"); }
        set { SetInSession("SomeInteger", value); }
    }
}

GetFromSession SetInSession - , . SomeInteger .

( ASP.NET MVC):

public class BaseController : Controller
{
    public ISessionWrapper SessionWrapper { get; set; }

    public BaseController()
    {
        SessionWrapper = new HttpContextSessionWrapper();
    }
}

Session, HttpContextSessionWrapper().

SessionWrapper ISessionWrapper Controller, HttpContext. , (int) Session [ "SomeInteger" ] SessionWrapper.SomeInteger. , ?

, Session, - BaseController, , .

+22

, , "" :

private T GetFromSessionStruct<T>(string key, T defaultValue = default(T)) where T : struct 
{
    object obj = HttpContext.Current.Session[key];
    if (obj == null)
    {
        return defaultValue;
    }
    return (T)obj;
}

private T GetFromSession<T>(string key) where T : class
{
    object obj = HttpContext.Current.Session[key];
    return (T)obj;
}

private T GetFromSessionOrDefault<T>(string key, T defaultValue = null) where T : class
{
    object obj = HttpContext.Current.Session[key];
    if (obj == null)
    {
        return defaultValue ?? default(T);
    }
    return (T)obj;
}

private void SetInSession<T>(string key, T value)
{
    if (value == null)
    {
        HttpContext.Current.Session.Remove(key);
    }
    else
    {
        HttpContext.Current.Session[key] = value;
    }
}
+2

All Articles