using System;
using System.Web;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BatchService.Framework.Utility
{
///
/// Cookie帮助类
///
public class Cookie
{
///
/// 取Cookie
///
///
///
public static HttpCookie Get(string name)
{
return HttpContext.Current.Request.Cookies[name];
}
///
/// 取Cookie值
///
///
///
public static string GetValue(string name)
{
var httpCookie = Get(name);
if (httpCookie != null)
return httpCookie.Value;
else
return string.Empty;
}
///
/// 移除Cookie
///
///
public static void Remove(string name)
{
Cookie.Remove(Cookie.Get(name));
}
public static void Remove(HttpCookie cookie)
{
if (cookie != null)
{
cookie.Expires = DateTime.Now;
Cookie.Save(cookie);
}
}
///
/// 保存Cookie
///
///
///
///
public static void Save(string name, string value, int expiresHours = 0)
{
var httpCookie = Get(name);
if (httpCookie == null)
httpCookie = Set(name);
httpCookie.Value = value;
Cookie.Save(httpCookie, expiresHours);
}
public static void Save(HttpCookie cookie, int expiresHours = 0)
{
//string domain = Fetch.ServerDomain;
//string urlHost = HttpContext.Current.Request.Url.Host.ToLower();
//if (domain != urlHost)
// cookie.Domain = domain;
//if (expiresHours > 0)
// cookie.Expires = DateTime.Now.AddMinutes(expiresHours);
//HttpContext.Current.Response.Cookies.Add(cookie);
Save(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, cookie, expiresHours * 60);
}
public static void Save(HttpContextBase context, HttpCookie cookie, int expiresMinutes = 0)
{
string domain = Fetch.ServerDomain;
string urlHost = context.Request.Url.Host.ToLower();
if (domain != urlHost)
cookie.Domain = domain;
if (expiresMinutes > 0)
cookie.Expires = DateTime.Now.AddMinutes(expiresMinutes);
context.Response.Cookies.Add(cookie);
}
public static HttpCookie Set(string name)
{
return new HttpCookie(name);
}
private static Dictionary sessionIdMap = new Dictionary();
private static Dictionary loginFailsMap = new Dictionary();
public static bool isValidUser(string id, bool isLogin=false)
{
string sessionId = HttpContext.Current.Session.SessionID;
if (isLogin)
{
sessionIdMap.Add(sessionId, id);
return true;
}
string historySessionId = sessionIdMap.ContainsKey(sessionId) ? sessionIdMap[sessionId] : "";
if (id!=historySessionId)
{
return false;
}
return true;
}
}
}