0

创建了这个简单的类来创建 cookie。但是一次又一次地创建cookie。

using System;
using System.IO;
using System.Web;
using System.Web.UI;

/// <summary>
/// Summary description for CookieHelper
/// </summary>
public class CookieHelper
{
    private Page _page = null;
    public bool success { get; private set; }

    public bool CreateSuccess { get; private set; }
    protected bool SaveSuccess { get; private set; }
    protected bool DeleteSuccess { get; private set; }

    public bool IsExisting { get;private set; }
    public string cookieName { get; set; }

    public CookieHelper(Page page)
    {
        _page = page;
        CreateSuccess = SaveSuccess = IsExisting = DeleteSuccess = false;
    }

    public bool Exist(string cookieName)
    {
        if (string.IsNullOrEmpty(cookieName))
            throw new ArgumentNullException("cookieName can't be null");
        else
        {
            try
            {
                if (_page.Request.Cookies[cookieName] == null)
                {
                    IsExisting = false;
                    return false;
                }
                else
                {
                    IsExisting = true;
                    return true;
                }
            }
            catch (ArgumentException)
            {
                throw new ArgumentException("cookieName given to Exist check function is invalid or not string");
            }
        }
    }

    public void CreateCookie(string cookieName, int expiryTimeInMinutes=1, bool secure = true)
    {
        if (string.IsNullOrEmpty(cookieName))
            throw new ArgumentNullException("cookieName can't be null");
        else
        {
            try
            {
                if (Exist(cookieName))
                {
                    IsExisting = true;
                    return;
                }
                else
                {
                    HttpCookie cookie=new HttpCookie(cookieName);
                    cookie.Expires = DateTime.Now.AddMinutes(expiryTimeInMinutes);
                    cookie.Secure = secure;
                    CreateSuccess = true;
                    IsExisting = true;
                }
            }
            catch (ArgumentException)
            {
                throw new ArgumentException(string.Format("CookieName type mismatch.  The parameter is of type '{0}', was expecting '{1}'.",
                    cookieName.GetType(), "a".GetType()));
            }
        }
    }

    public bool SaveInCookie(string cookieName, string valueKey, string valueToBeStored, int expiryTimeInMinutes, bool secure = true)
    {
        SaveSuccess = false;
        if (typeof(string) != cookieName.GetType() || typeof(string) != valueKey.GetType() || typeof(string) != valueToBeStored.GetType() || typeof(bool) != secure.GetType() || typeof(int) != expiryTimeInMinutes.GetType())
            throw new ArgumentException("Parameter type mismatch");
        else
        {
            try
            {
                HttpCookie cookie = null;
                if (_page.Request.Cookies[cookieName] == null)
                {
                    cookie = new HttpCookie(cookieName);
                    CreateSuccess = true;
                    IsExisting = true;
                }
                else
                {
                    cookie = _page.Request.Cookies[cookieName];
                    IsExisting = true;
                    CreateSuccess = false;
                }

                cookie.Values.Add(valueKey, valueToBeStored);
                cookie.Expires = DateTime.Now.AddMinutes(expiryTimeInMinutes);
                cookie.Secure = secure;
                _page.Response.Cookies.Add(cookie);
            }
            catch (Exception)
            {
                SaveSuccess = false;
                throw new Exception("Cookie Save Failed");
            }
            return SaveSuccess;
        }
    }

    public string GetCookieValue(string cookieName, string valueKey = null)
    {
        if (typeof(string) != cookieName.GetType() || typeof(string) != valueKey.GetType())
            throw new ArgumentException("Parameter type mismatch");
        else
        {
            string keyExist = string.Empty;
            try
            {
                if (Exist(cookieName) == IsExisting)
                {
                    keyExist = (string)_page.Request.Cookies[cookieName][valueKey];
                    return ((string.IsNullOrEmpty(keyExist)) ? String.Empty : _page.Request.Cookies[cookieName].Values[valueKey]
                        );
                }
                else
                    throw new FileNotFoundException("Cookie with the name provided doesnot exist");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    public bool DeleteCookie(string cookieName)
    {
        if (typeof(string) != cookieName.GetType())
            throw new ArgumentException("Parameter type mismatch");
        else
        {
            try
            {
                if (_page.Request.Cookies[cookieName] != null)
                {
                    HttpCookie myCookie = new HttpCookie(cookieName);
                    myCookie.Expires = DateTime.Now.AddDays(-1d);
                    _page.Response.Cookies.Add(myCookie);
                    IsExisting = false;
                }
                return true;
            }
            catch (Exception ex)
            { throw ex; }
        }
    }
}

在我的网页中将此类称为-

protected void Page_Load(object sender, EventArgs e)
    {
        CookieHelper cook = new CookieHelper(this.Page);
        if (!cook.Exist("Preferences"))
        {
            cook.CreateCookie("Preferences",2);
            Response.Write("Created");
        }
        else
            Response.Write("Not");

    }

给我总是创造。我添加了断点并检查了调试,发现编译器总是去创建部分。请建议我创建这个助手类。

4

1 回答 1

0

看来你不见了

Response.Cookies.Add(myCookie);

在你的CreateCookie其他情况下。

因此它看起来像:

HttpCookie cookie=new HttpCookie(cookieName);
cookie.Expires = DateTime.Now.AddMinutes(expiryTimeInMinutes);
cookie.Secure = secure;
CreateSuccess = true;
IsExisting = true;
Response.Cookies.Add(myCookie);

这确保了 cookie 被添加到响应中,因此浏览器每次访问时都知道重播它。

这是获取有关 Web 表单环境中 cookie 信息的良好起点

于 2013-04-20T21:36:23.903 回答