如何覆盖System.Web.HttpContext.Current.Session(MVC4)

时间:2016-10-12 11:22:07

标签: c# asp.net-mvc-4 session

我试图覆盖System.Web.HttpContext.Current.Session["foo"]

我的问题是系统已经在使用System.Web.HttpContext.Current.Session,我想在每个会话名称上添加一个guid。 (太多无法替换)

例如System.Web.HttpContext.Current.Session[guid + "foo"]

我是否可以覆盖getset属性?

1 个答案:

答案 0 :(得分:0)

如果您不想使用扩展方法并更改调用字符串索引器的所有已实现的代码,那么您可以滚动自己的提供程序并在那里执行。见Implementing a Session-State Store Provider。然后,您可以在那里实现“guid前缀”。

以下是扩展方法的示例。我不知道你从哪里得到guid,你从来没有提到这个,但你可以拿这个例子并自己添加。

public static class HttpSessionStateExtension
{
    public static object Get(this System.Web.SessionState.HttpSessionState session, string key)
    {
        var guid = ???; // no idea where or how you are getting guid, you never explained that in your question
        return session[guid + key];
    }
}

// in other methods you can then call it the same as you would the indexer
var result = System.Web.HttpContext.Current.Session.Get("foo");