使用会话包装器替换对会话变量的直接调用

时间:2011-05-04 08:57:43

标签: asp.net asp.net-mvc-3

我使用这样的会话包装器:

public interface ISessionWrapper
{
   // ...
   CultureInfo Culture { get; set; }
}

public class SessionWrapper: 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 CultureInfo Culture
    {
        get { return GetFromSession<CultureInfo>("Culture"); }
        set { SetInSession("Culture", value); }
    }
}

我可以在我的控制器中使用这个界面,如下所示:

private readonly ISessionWrapper sessionWrapper = new SessionWrapper();
// ...
ci = new CultureInfo(langName);
sessionWrapper.Culture = ci;

但是如何在下面的视图中访问此包装以替换(直接调用)会话变量?

@switch (Session["Culture"].ToString()) 
{    
    case "fr":  
        // ...

    case "uk":  
        // ...
}

1 个答案:

答案 0 :(得分:2)

您可以使用基本视图:

public abstract class BaseViewPage : WebViewPage
{
    public virtual ISessionWrapper SessionWrapper
    {
        get
        {
            return new SessionWrapper();
        }
    }
}

public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
{
    public virtual ISessionWrapper SessionWrapper
    {
        get
        {
            return new SessionWrapper();
        }
    }
}

您的观点可以访问SessionWrapper属性。

确保添加pageBaseType =&#34; SessionWrapper&#34;属性为web.config中的pages标记。