// ***********************************************************************
// Assembly : Infrastructure
// Author : Administrator
// Created : 09-22-2015
//
// ***********************************************************************
//
// Copyright (c) . All rights reserved.
//
// Cookie辅助
// ***********************************************************************
using System;
using System.Web;
namespace Infrastructure
{
///
/// Cookie帮助类
///
public class CookieHelper
{
///
/// 写cookie值
///
/// 名称
/// 值
public static void WriteCookie(string strName, string strValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(cookie);
}
///
/// 写cookie值
///
/// 名称
/// 值
/// 过期时间(分钟)
public static void WriteCookie(string strName, string strValue, int expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
///
/// 读cookie值
///
/// 名称
/// cookie值
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
///
/// Get cookie expiry date that was set in the cookie value
///
///
///
public static DateTime GetExpirationDate(HttpCookie cookie)
{
if (String.IsNullOrEmpty(cookie.Value))
{
return DateTime.MinValue;
}
string strDateTime = cookie.Value.Substring(cookie.Value.IndexOf("|") + 1);
return Convert.ToDateTime(strDateTime);
}
///
/// Set cookie value using the token and the expiry date
///
///
///
///
public static string BuildCookueValue(string value, int minutes)
{
return String.Format("{0}|{1}", value, DateTime.Now.AddMinutes(minutes).ToString());
}
///
/// Reads cookie value from the cookie
///
///
///
public static string GetCookieValue(HttpCookie cookie)
{
if (String.IsNullOrEmpty(cookie.Value))
{
return cookie.Value;
}
return cookie.Value.Substring(0, cookie.Value.IndexOf("|"));
}
}
}