/******************************************************************************
* 作者: 季健国
* 创建时间: 2012/6/6 22:19:49
*
*
******************************************************************************/
using System;
using System.Web;
namespace Ant.Service.Common
{
///
/// Cookie辅助类
///
public class CookieHelper
{
///
/// 清除指定Cookie
///
/// cookiename
public static void ClearCookie(string cookiename)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-14400);
HttpContext.Current.Response.Cookies.Remove(cookiename);
HttpContext.Current.Response.AppendCookie(cookie);
}
}
///
/// 获取指定Cookie值
///
/// cookiename
///
public static string GetCookieValue(string cookiename)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
string str = string.Empty;
if (cookie != null)
{
str = cookie.Value;
}
return str;
}
///
/// 获取cookie
///
///
///
public static HttpCookie GetCookie(string cookiename)
{
return HttpContext.Current.Request.Cookies[cookiename];
}
///
/// 添加一个Cookie,默认浏览器关闭过期
///
public static void SetCookie(string cookiename, System.Collections.Specialized.NameValueCollection cookievalue,int? days)
{
var cookie = HttpContext.Current.Request.Cookies[cookiename];
if (cookie == null)
{
cookie = new HttpCookie(cookiename);
cookie.Values.Add(cookievalue);
var siteurl = System.Configuration.ConfigurationManager.AppSettings["siteurl"];
if (!string.IsNullOrEmpty(siteurl))
{
cookie.Domain = siteurl.Replace("www.", "");
}
if (days != null && days > 0) { cookie.Expires = DateTime.Now.AddDays(Convert.ToInt32(days)); }
HttpContext.Current.Response.AppendCookie(cookie);
}
else
{
HttpContext.Current.Response.SetCookie(cookie);
}
}
///
/// 添加一个Cookie
///
/// cookie名
/// cookie值
/// 过期时间 null为浏览器过期
public static void SetCookie(string cookiename, string cookievalue, int? expires)
{
var cookie = HttpContext.Current.Request.Cookies[cookiename];
if (cookie == null)
{
cookie = new HttpCookie(cookiename);
cookie.Value = cookievalue;
var siteurl = System.Configuration.ConfigurationManager.AppSettings["siteurl"];
if (!string.IsNullOrEmpty(siteurl))
{
cookie.Domain = siteurl.Replace("www.", "");
}
if (expires != null && expires > 0) { cookie.Expires = DateTime.Now.AddDays(Convert.ToInt32(expires)); }
HttpContext.Current.Response.AppendCookie(cookie);
}
else
{
HttpContext.Current.Response.SetCookie(cookie);
}
}
}
}