大家都知道,网站一般都会用Session保存用户的ID,但是容易过期,经常丢失,然而用Cookies就比较好了,下面就是我的读写Cookies的代码。
/// <summary>
/// 写Cookies
/// </summary>
/// <param name="response"></param>
/// <param name="request"></param>
/// <param name="server"></param>
/// <param name="IndexValue"></param>
/// <param name="TextValue"></param>
/// <param name="ExpriesHour">设置的过期时间</param>
public void WriteCookies(HttpResponse response,HttpRequest request,HttpServerUtility server,string IndexValue,string TextValue,int ExpriesHour)
{
response.Cookies[IndexValue].Value = TextValue;
response.Cookies[IndexValue].Expires = System.DateTime.Now.AddHours(ExpriesHour);
}
/// <summary>
/// 读Cookies
/// </summary>
/// <param name="response"></param>
/// <param name="request"></param>
/// <param name="server"></param>
/// <param name="IndexValue"></param>
/// <returns></returns>
public string ReadCookies(HttpResponse response, HttpRequest request, HttpServerUtility server, string IndexValue)
{
if (request.Cookies[IndexValue] != null)
return request.Cookies[IndexValue].Value.ToString();
return "";
}
/// <summary>
/// 删除Cookies,立即过期
/// </summary>
/// <param name="response"></param>
/// <param name="request"></param>
/// <param name="server"></param>
/// <param name="IndexValue"></param>
public void DeleteCookies(HttpResponse response, HttpRequest request, HttpServerUtility server, string IndexValue)
{
if (request.Cookies[IndexValue] != null)
{
HttpCookie cookies=request .Cookies[IndexValue];
cookies .Expires=System.DateTime.Now.AddHours(-1);
response.Cookies.Add(cookies);
}
}
/// 写Cookies
/// </summary>
/// <param name="response"></param>
/// <param name="request"></param>
/// <param name="server"></param>
/// <param name="IndexValue"></param>
/// <param name="TextValue"></param>
/// <param name="ExpriesHour">设置的过期时间</param>
public void WriteCookies(HttpResponse response,HttpRequest request,HttpServerUtility server,string IndexValue,string TextValue,int ExpriesHour)
{
response.Cookies[IndexValue].Value = TextValue;
response.Cookies[IndexValue].Expires = System.DateTime.Now.AddHours(ExpriesHour);
}
/// <summary>
/// 读Cookies
/// </summary>
/// <param name="response"></param>
/// <param name="request"></param>
/// <param name="server"></param>
/// <param name="IndexValue"></param>
/// <returns></returns>
public string ReadCookies(HttpResponse response, HttpRequest request, HttpServerUtility server, string IndexValue)
{
if (request.Cookies[IndexValue] != null)
return request.Cookies[IndexValue].Value.ToString();
return "";
}
/// <summary>
/// 删除Cookies,立即过期
/// </summary>
/// <param name="response"></param>
/// <param name="request"></param>
/// <param name="server"></param>
/// <param name="IndexValue"></param>
public void DeleteCookies(HttpResponse response, HttpRequest request, HttpServerUtility server, string IndexValue)
{
if (request.Cookies[IndexValue] != null)
{
HttpCookie cookies=request .Cookies[IndexValue];
cookies .Expires=System.DateTime.Now.AddHours(-1);
response.Cookies.Add(cookies);
}
}