【问题标题】:Asp.net HttpCookie Read/Write problemAsp.net HttpCookie 读/写问题
【发布时间】:2011-11-22 08:31:14
【问题描述】:

我一直在寻找解决这个问题的方法,但我找不到。顺便说一句,我无法理解我的问题的原因。

问题是:

我的 Web 应用程序有一个登录页面,并从 cookie 获取登录的用户 ID。它以前工作过,但 5-6 天前因为发生了一些变化,它不适用于 IE。现在它不适用于任何浏览器。

我可以在 Chrome 中看到 cookie。使用 Internet Explorer 开发工具查看时,有时 cookie 已写入但 IE 仍无法读取

我的网络应用在 Windows Server 2008 R2 BTW 上

设置我的 web.config:

<httpCookies domain=".domainname.com" httpOnlyCookies="false" requireSSL="false" />

这是我的 SetCookie 代码

<!-- language: c# -->
string uId = "userID";
DateTime expireDate = DateTime.Now.AddDays(3);
HttpContext.Current.Response.Cookies["cookieName"]["uID"] = uId;
HttpCookie aCookie = new HttpCookie("cookieName");

aCookie.Values["uID"] = uId;
aCookie.Path = "/";
aCookie.Expires = expireDate;
aCookie.HttpOnly = false;
aCookie.Domain = "domainname.com";
aCookie.Name = "cookieName";
HttpContext.Current.Response.Cookies.Add(aCookie);

还有这个 GetCookie 代码

<!-- language: c# -->
if (HttpContext.Current.Request.Cookies["cookieName"] != null)
{
    System.Collections.Specialized.NameValueCollection UserInfoCookieCollection;
    UserInfoCookieCollection = HttpContext.Current.Request.Cookies["cookieName"].Values;
    userID = HttpContext.Current.Server.HtmlEncode(UserInfoCookieCollection["uID"]);
}

场景是:

正在尝试登录

SetCookie 方法触发

SetCookie 方法的结尾有两个 cookie "cookieName" 和 "ASP.NET 会话 ID"

GetCookie 方法触发

只有“ASP.NET SessionId”和会话值仍然相同

感谢您的帮助。

【问题讨论】:

    标签: asp.net session cookies


    【解决方案1】:

    我的问题解决了。将我的代码更改为此

                string uId = "userID";
                DateTime expireDate = DateTime.Now.AddDays(3);
    
                var httpCookie = HttpContext.Current.Response.Cookies["cookieName"];
                if (httpCookie != null)
                {
                    httpCookie["uID"] = uId;
    
                    HttpContext.Current.Response.Cookies.Add(httpCookie);
                }
                else
                {
                    HttpCookie aCookie = new HttpCookie("cookieName");
                    aCookie.Values["uID"] = uId;
                    aCookie.Expires = expireDate;
    
                    HttpContext.Current.Response.Cookies.Add(aCookie);
                }
    

    【讨论】:

      【解决方案2】:

      这个让我难过。但设法解决它如下。所以基本上将到期设置为初始化程序的一部分是行不通的。在将 cookie 添加到响应对象后设置它有效!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-12
        • 2021-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多