我正在使用C#。
我的 SESSION变量[“FROMDATA”] 中有以下格式值,我使用 DICTIONARY 来存储FORM已发布数据。请参阅相关的question。
以下是我的SESSION变量中的一些值。
1) key - "skywardsNumber" value-"99999039t"
2) key - "password" value-"a2222222"
3) key - "ctl00$MainContent$ctl22$FlightSchedules1$ddlDepartureAirport-suggest" value-"London"
4) key - "ctl00$MainContent$ctl22$ctl07$txtPromoCode" value-"AEEGIT9"
.
.
....so on
现在我想使用 METHOD 创建一个CLASS ,我将在其中传递“KEY”,它将首先检查 NULL或EMPTY ,然后从SESSION变量[“FROMDATA”] 返回其值。
请建议使用C#。
答案 0 :(得分:5)
试试这个,
public class Test
{
public static string GetValue(string key)
{
string value = string.Empty;
if (HttpContext.Current.Session["FROMDATA"] != null)
{
Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session["FROMDATA"];
if(form.ContainsKey(key))
value = form[key];
}
return value;
}
}
编辑:
public static string GetValue(string sessionkey,string key)
{
string value = string.Empty;
if (HttpContext.Current.Session[sessionkey] != null)
{
Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session[sessionkey];
if(form.ContainsKey(key))
value = form[key];
}
return value;
}
答案 1 :(得分:0)
试试这个:你必须稍微调整它才能编译。但是你会得到基本的想法
public class Session
{
private const string _skyWardsNumber = "skyWardsNumber";
// Add other keys here
public string SkyWardsNumber
{
get
{
object str = (ReadFromDictionary(_skyWardsNumber);
if (str != null)
{
return (string) str;
}
else
{
return string.Empty;
}
}
set
{
WriteToDictionary(_skyWardsNumber, value);
}
}
public object ReadFromDictionary(string key)
{
IDictionary dictionary = (ReadFromContext("Dictionary") as IDictionary);
if (dictionary != null && dictionary.ContainsKey(key))
{
return dictionary[key];
}
else
{
return null;
}
}
public object WriteFromDictionary(string key, object value)
{
IDictionary dictionary = (ReadFromContext("Dictionary") as IDictionary);
if(dictionary == null)
WriteToContext("Dictionary", new Dictionary<string, string>())
dictionary = (ReadFromContext("Dictionary") as IDictionary);
if (dictionary.ContainsKey(key))
{
dictionary[key] = value;
}
else
{
dictionary.Add(//add new keyvaluepair.);
}
}
private static void WriteToContext(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
private static object ReadFromContext(string key)
{
if(HttpContext.Current.Session[key] != null)
return HttpContext.Current.Session[key] as object;
return null;
}
}