对我来说,我发现它HttpContext.Current
是空的,所以我创建了它:
System.Web.HttpContext c = System.Web.HttpContext.Current;
然后我将它传递到我的另一个类中的函数中,如下所示:
string myString = "Something to save";
SessionExtensions.SetDataToSession<string>(c, "MyKey1", myString);
我实际上希望我的函数成为一个真正的扩展方法,Session
就像下面的那样,但我发现它this HttpSessionStateBase session
是空的,NullReferenceException
当我尝试添加任何东西来Session
使用它时,它会给出。所以这:
public static class SessionExtensions
{
/// <summary>
/// Get value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="session"></param>
/// <param name="key"></param>
/// <returns></returns>
public static T GetDataFromSession<T>(this HttpSessionStateBase session, string key)
{
return (T)session[key];
}
/// <summary>
/// Set value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="session"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetDataToSession<T>(this HttpSessionStateBase session, string key, object value)
{
session[key] = value;
}
}
微软在这里: https ://code.msdn.microsoft.com/How-to-create-and-access-447ada98变成了这个,而不是:
public static class SessionExtensions
{
/// <summary>
/// Get value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="session"></param>
/// <param name="key"></param>
/// <returns></returns>
public static T GetDataFromSession<T>(HttpContext context, string key)
{
if (context != null && context.Session != null)
{
context.Session.Abandon();
}
return (T)context.Session[key];
}
/// <summary>
/// Set value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="session"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetDataToSession<T>(HttpContext context, string key, object value)
{
context.Session[key] = value;
}
}
我能够像这样检索我的数据:
System.Web.HttpContext c = System.Web.HttpContext.Current;
string myString = SessionExtensions.GetDataFromSession<string>(c, "MyKey1");
而且,当然,既然HttpContext.Current
和Session
现在存在,我什至可以将其简化为:
string myString = Session["MyKey1"].ToString();
如果这是对象,您可以将对象的类型放在<string>
函数中SetDataToSession()
:
List<string> myStringList = new List<string>();
myStringList.Add("Something to save");
SessionExtensions.SetDataToSession<List<string>>(c, "MyKey1", myStringList);
并检索它:
System.Web.HttpContext c = System.Web.HttpContext.Current;
List<string> myStringList = SessionExtensions.GetDataFromSession<List<string>>(c, "MyKey1");
或者简单地说:
List<string> myStringList = (List<string>)Session["MyKey1"];