博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

session和ip绑定的简便方法

Posted on 2012-03-23 17:32  ForXiXi  阅读(2863)  评论(0编辑  收藏  举报

写:SessionHelper.Add("MemberName", “abc”);

读: var MemberName= SessionHelper.Get<string>("MemberName");

 

 

sessionHelper里面只需要简单把KeyName和IP重新组合成一个新的KeyName,然后存取数据即可

private static string FormatKey(string key)
{
  key = key.Replace(".", "");
  return string.Format("{0}.{1}", key, Webhelper.Utils.GetClientIPdata(true));
}

public static T Get<T>(string key)
{
var value=HttpContext.Current.Session[FormatKey(key)];
if (value != null)
{
return (T)value;
}
else
{
return default(T);
}
}

public static void Add(string key, object value)
{
 StoreFormattedKey(FormatKey(key), value);
}

private static void StoreFormattedKey(string formattedKey, object value)
{
HttpContext.Current.Session[formattedKey] = value;
}

记事本代码 可能有误 请谅解

 

最后说一个问题,此处的getIP,如果用户使用了代理,建议直接使用代理的IP,不建议使用HTTP_X_FORWARDED_FOR,个人感觉不是很安全