首页 > 代码库 > C#中Cookies的存取
C#中Cookies的存取
<1>
C#中Cookies的存取
[csharp] view plaincopy
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace WebApplication1
- {
- public class FunCookie
- {
- /// <summary>
- /// 创建Cookie和赋值,及设计Cookie有效天数
- /// </summary>
- /// <param name="strCookieName">Cookie名字</param>
- /// <param name="strCookieValue">Cookie的值</param>
- /// <param name="intDay">Cookie有效天数</param>
- /// <returns>布尔值</returns>
- public static bool SetCookie(string strCookieName,string strCookieValue,int intDay )
- {
- try
- {
- HttpCookie cookie = new HttpCookie(strCookieName); //创建一个cookie对象
- cookie.Value = strCookieValue; //设置cookie的值
- cookie.Expires = DateTime.Now.AddDays(intDay); //或cookie.Expires.AddDays(intDay);设置cookie的有效期
- System.Web.HttpContext.Current.Response.Cookies.Add(cookie); //将cookie添加到cookies中
- return true;
- }
- catch
- {
- return false;
- }
- }
- /// <summary>
- /// 根据Cookie的名字获取Cookie的值
- /// </summary>
- /// <param name="strCookieName">要获取的Cookie的名字</param>
- /// <returns>Cookie的值(string类型)</returns>
- public static string GetCookie(string strCookieName)
- {
- HttpCookie cookie= HttpContext.Current.Request.Cookies[strCookieName];//获取cookie
- if (cookie != null)
- {
- return cookie.Value; //返回cookie的值
- }
- else
- {
- return null;
- }
- }
- /// <summary>
- /// 删除Cookie
- /// </summary>
- /// <param name="strCookieName"></param>
- /// <returns></returns>
- public static bool DeleteCookie(string strCookieName)
- {
- try
- {
- HttpCookie cookie = new HttpCookie(strCookieName);
- cookie.Expires = DateTime.Now.AddDays(-1);
- HttpContext.Current.Response.Cookies.Add(cookie);
- return true;
- }
- catch
- {
- return false;
- }
- }
- }
- }
C#中Cookies的存取
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。