C# HttpCookie在本地工作,但不在服务器上工作
我的cookie管理代码有问题。在每一页上,我都会查看是否设置了键值。我的问题是,查看cookie会创建一个空cookie 在本地,我可以查看cookie,然后设置键值,一切正常。但是,当我将代码移动到测试服务器时,一切行为都不同。例如,本地只发布一个cookie(显示在chrome的工具中)。在服务器上,发出两个具有相同代码的cookie 我大约在4年前写过这段代码,它是为.NET2.0设计的,当时HttpCookie的行为发生了改变,因此查看cookie会创建一个空的,如果它不存在的话。以前,在.Net 1.1中返回null。现在我想知道在2.0和4.0之间发生了一些根本性的变化 我应该注意到,我的本地机器是Windows7,服务器是Windows2003服务器——这不应该有任何区别。唯一需要注意的是,应用程序正在服务器上的虚拟目录中运行。这是否会成为问题的一部分?我不确定。我尝试将cookie的路径设置为虚拟目录的路径,但没有成功 My cookie有几个层,包括一个用于直接处理http cookie的基本层,一个可以打开或关闭以进行调试的加密层,以及一个管理层。我将分享我的代码,希望我的逻辑中有一个明显的错误 我还想提到的是,我正在使用FormsAuthenticationCookie进行其他用途。此cookie用于一些无关但必需的数据 我的基本cookie层:C# HttpCookie在本地工作,但不在服务器上工作,c#,visual-studio-2008,.net-4.0,windows-server-2003,httpcookie,C#,Visual Studio 2008,.net 4.0,Windows Server 2003,Httpcookie,我的cookie管理代码有问题。在每一页上,我都会查看是否设置了键值。我的问题是,查看cookie会创建一个空cookie 在本地,我可以查看cookie,然后设置键值,一切正常。但是,当我将代码移动到测试服务器时,一切行为都不同。例如,本地只发布一个cookie(显示在chrome的工具中)。在服务器上,发出两个具有相同代码的cookie 我大约在4年前写过这段代码,它是为.NET2.0设计的,当时HttpCookie的行为发生了改变,因此查看cookie会创建一个空的,如果它不存在的话。以前
public abstract class BaseCookie
{
#region Private Variables
private string cookieName;
private int timeout = 30;
private ExpirationMode expirationMode = ExpirationMode.SlidingExpiration;
private string domain;
private bool httpOnly = true;
private string path = "/";
private bool secure;
private string cookieValue;
#endregion
#region Public Properties
/// <summary>
/// The name of the cookie as it appears in the request and response
/// </summary>
protected string CookieName
{
get { return cookieName; }
set { cookieName = value; }
}
/// <summary>
/// The expiration mode of the cookie (default SlidingExpiration)
/// </summary>
public ExpirationMode ExpirationMode
{
get { return expirationMode; }
}
/// <summary>
/// The timeout in minutes (default 30)
/// </summary>
public int Timeout
{
get { return timeout; }
set { timeout = value; }
}
/// <summary>
/// The cookie domain (default String.Empty)
/// </summary>
public string Domain
{
get { return domain; }
set { domain = value; }
}
/// <summary>
/// Whether or not the cookie is http only (default true)
/// </summary>
public bool HttpOnly
{
get { return httpOnly; }
set { httpOnly = value; }
}
/// <summary>
/// The path of the cookie (default "/")
/// </summary>
public string Path
{
get { return path; }
set { path = value; }
}
/// <summary>
/// Whether or not the cookie supports https (default false)
/// </summary>
public bool Secure
{
get { return secure; }
set { secure = value; }
}
/// <summary>
/// The Value of the cookie (NOTE: this should only be used for setting the value when calling AppendNewCookie().
/// This will not change the value of the cookie after initialization. Use SetCookieValue and GetCookieValue after initialization.
/// </summary>
public string Value
{
get { return cookieValue; }
set { cookieValue = value; }
}
/// <summary>
/// The cookie in the Request
/// </summary>
private HttpCookie RequestCookie
{
get
{
return HttpContext.Current.Request.Cookies.Get(CookieName);
}
}
/// <summary>
/// The cookie in the Response
/// </summary>
private HttpCookie ResponseCookie
{
get
{
return HttpContext.Current.Response.Cookies.Get(CookieName);
}
}
#endregion
#region Constructors
/// <summary>
/// Constructor setting the name of the cookie with Sliding Expiration
/// </summary>
/// <param name="cookieName">the name of the cookie</param>
public BaseCookie(string cookieName)
: this(cookieName, ExpirationMode.SlidingExpiration)
{
}
/// <summary>
/// Constructor setting the name of the cookie and the expiration mode
/// </summary>
/// <param name="cookieName">the name of the cookie</param>
/// <param name="expirationMode">the Olympus.Cookies.ExpirationMode of the cookie</param>
public BaseCookie(string cookieName, ExpirationMode expirationMode)
{
this.cookieName = cookieName;
CookieConfig config = Configuration.CookieConfiguration.Cookies[cookieName];
if (config != null)
{
Domain = config.Domain;
HttpOnly = config.HttpOnly;
Path = config.Path;
Secure = config.Secure;
Timeout = config.Timeout;
}
//EnsureCookie();
}
#endregion
/// <summary>
/// This method ensures that the cookie is not empty if it exists in either the request or response.
/// Due to changes in the cookie model for 2.0, this step is VITAL to cookie management.
/// </summary>
protected void EnsureCookie()
{
//if the cookie doesn't exist in the response (hasn't been altered or set yet this postback)
if (IsNull(ResponseCookie))
{
//if the cookie exists in the request
if (!IsNull(RequestCookie))
{
//get the cookie from the request
HttpCookie cookie = RequestCookie;
//update the expiration
if (ExpirationMode == ExpirationMode.NoExpiration)
{
cookie.Expires = DateTime.Now.AddYears(10);
}
else
{
cookie.Expires = DateTime.Now.AddMinutes(Timeout);
}
//set the cookie into the response
HttpContext.Current.Response.Cookies.Set(cookie);
}
else
{
//if the response and request cookies are null, append a new cookie
AppendNewCookie();
}
}
}
/// <summary>
/// Append an empty cookie to the Response
/// </summary>
public virtual void AppendNewCookie()
{
HttpCookie cookie = new HttpCookie(CookieName);
cookie.Domain = Domain;
cookie.HttpOnly = HttpOnly;
cookie.Path = Path;
cookie.Secure = Secure;
cookie.Value = Value;
if (ExpirationMode == ExpirationMode.NoExpiration)
{
cookie.Expires = DateTime.Now.AddYears(10);
}
else
{
cookie.Expires = DateTime.Now.AddMinutes(Timeout);
}
HttpContext.Current.Response.Cookies.Add(cookie);
}
/// <summary>
/// Determine if the Cookie is null.
/// </summary>
/// <remarks>
/// Due to changes in the 2.0 cookie model, looking in the request or respnse creates an empty cookie with an
/// expiration date of DateTime.MinValue. Previously, a null value was returned. This code calls one of these
/// empty cookies a null cookie.
/// </remarks>
/// <param name="cookie">the cookie to test</param>
/// <returns>System.Boolean true if the cookie is "null"</returns>
protected static bool IsNull(HttpCookie cookie)
{
if (cookie == null)
{
return true;
}
else
{
if (String.IsNullOrEmpty(cookie.Value) && cookie.Expires == DateTime.MinValue)
{
return true;
}
}
return false;
}
/// <summary>
/// Update the expiration of the response cookie
/// <remarks>
/// If this is not done, the cookie will never expire because it will be updated with an expiry of DateTime.Min
/// </remarks>
/// </summary>
protected void SetExpiration()
{
if (ExpirationMode == ExpirationMode.NoExpiration)
{
ResponseCookie.Expires = DateTime.Now.AddYears(10);
}
else
{
ResponseCookie.Expires = DateTime.Now.AddMinutes(Timeout);
}
}
/// <summary>
/// Set the value of a cookie.
/// </summary>
/// <remarks>
/// Setting value will override all attributes.
/// </remarks>
/// <param name="value">the value to set the cookie</param>
public virtual void SetCookieValue(string value)
{
//EnsureCookie();
ResponseCookie.Value = value;
SetExpiration();
}
/// <summary>
/// Get the default value (the first value) of the cookie
/// </summary>
/// <remarks>
/// Getting the value only returns the first value (values[0]) because it has no key.
/// </remarks>
/// <returns>System.String</returns>
public virtual string GetCookieValue()
{
//EnsureCookie();
string returnValue = "";
if (RequestCookie.Values.Count > 0)
{
returnValue = RequestCookie.Values[0];
}
return returnValue;
}
/// <summary>
/// Set a key/value pair
/// </summary>
/// <param name="key">the key for the pair</param>
/// <param name="value">the value to assign to the key</param>
public virtual void SetKeyValue(string key, string value)
{
//EnsureCookie();
ResponseCookie.Values.Set(key, value);
SetExpiration();
}
/// <summary>
/// Get a value for a given key
/// </summary>
/// <param name="key">the key to find a value of</param>
/// <returns>System.String</returns>
public virtual string GetKeyValue(string key)
{
//EnsureCookie();
return RequestCookie.Values[key];
}
/// <summary>
/// Expire the cookie
/// </summary>
public virtual void Expire()
{
//Setting the expiration does not remove the cookie from the next request
ResponseCookie.Expires = DateTime.Now.AddDays(-1);
}
}
最后,是完成这一切的cookie管理层
public sealed class Cookie
{
string cookieName;
public Cookie(string cookieName)
{
this.cookieName = cookieName;
}
public void AppendCookie()
{
EncryptedCookie cookie = new EncryptedCookie(cookieName);
cookie.AppendNewCookie();
}
public void SetAttribute(string attributeName, string attributeValue)
{
EncryptedCookie cookie = new EncryptedCookie(cookieName);
cookie.SetKeyValue(attributeName, attributeValue);
}
public void SetValue(string value)
{
EncryptedCookie cookie = new EncryptedCookie(cookieName);
cookie.SetCookieValue(value);
}
public string GetValue()
{
EncryptedCookie cookie = new EncryptedCookie(cookieName);
return cookie.GetCookieValue();
}
public string GetAttribute(string attributeName)
{
EncryptedCookie cookie = new EncryptedCookie(cookieName);
return cookie.GetKeyValue(attributeName);
}
}
还有一个自定义配置可以帮助配置cookie。下面是它的样子:
<cookie>
<cookies>
<!-- enableEncryption: [ true | false ] -->
<!-- expirationMode: [ SlidingExpiration | NoExpiration ] -->
<!-- timeout: the timeout in minutes (Default 30)-->
<!-- httpOnly: [ true | false ] -->
<!-- secure: [ true | false ] -->
<add name="MyCookie" enableEncryption="true" expirationMode="SlidingExpiration" timeout="64800" domain="" httpOnly="true" path="" secure="false" />
</cookies>
</cookie>
我首先调用属性以查看是否已设置用户的ID。此调用在每一页上都完成。然后在另一个页面上,用户可以进行身份验证,我将ID设置到cookie中。这一切都可以在本地运行,但是如果我点击服务器上的主页(id在其中查找id),然后进行身份验证,则不会设置cookie值。它仍然为空。当您在HttpContext.Current.Response上检查cookie时,会创建cookie。我通过在设置cookie时将cookie的副本粘贴到HttpContext.Current.Items中来解决这个问题。然后,当我需要检查它是否已设置时,我会检查项目而不是Response.Cookies
这不是最优雅的解决方案,但它可以完成任务。是您不想打电话的问题
cookie.AppendCookie();
在MyId的集合访问器中?您正在用SetMyId方法调用它。Win 7和Win Server 2003非常不同-Win 7有IIS7,服务器使用IIS6。您是在Cassini(Visual Studio的服务器)还是在本地IIS上运行此功能?在服务器上,使用设置的两个cookie和上面的配置,一个设置为“/”作为路径,另一个设置为“/MyVirtualDir”作为路径。设置cookie的路径并没有改变这一点。@davisoa-是的,Cassini在本地,IIS6在服务器上。但是,该代码是为.net 2.0设计的,它所在的库已升级到4.0。我使用端口(而不是默认站点的虚拟目录)添加了一个新的IIS站点。现在我的饼干开始工作了。我的配置有问题吗?虚拟目录的某些内容可能不太好。现在,突然间,它在本地不起作用了。这是令人沮丧的。即使当我看到虚拟对象时,它是被创建的,我也会把它拉出来,并试图在其中设置值。不让我这么做是没有道理的嗯,它是在本地完成的,只是不在服务器上。说我不必。我可以直接在集合中修改cookie,但您使用的是Get方法来检索cookie,而不是示例中使用的项访问器。我认为使用Get来检索cookie意味着必须使用Set来更新响应cookie集合中的cookie。这种行为非常奇怪。它在工作,然后停止了。我将放弃上面的代码,并按照MSDN文章所说的方式来做。
public int MyId
{
get
{
Cookie cookie = new Cookie(ConfigurationHelper.Cookies.MyCookie);
int myId= 0;
try
{
Int32.TryParse(cookie.GetAttribute(BILLERID_KEY), out myId);
}
catch (System.NullReferenceException)
{
//do nothing on purpose.
}
return myId;
}
set
{
Cookie cookie = new Cookie(ConfigurationHelper.Cookies.MyCookie);
cookie.SetAttribute(MY_KEY, value.ToString());
}
}
public void SetMyId(int myId)
{
Cookie cookie = new Cookie(ConfigurationHelper.Cookies.MyCookie);
cookie.SetAttribute(MYID_KEY, myId.ToString());
cookie.AppendCookie();
}
cookie.AppendCookie();