开发者

Asp.net HttpCookie Read/Write problem

开发者 https://www.devze.com 2023-04-06 18:36 出处:网络
I\'ve been searching a solut开发者_运维问答ion for this problem but i couldn\'t have one. By the way i can\'t understand the reason of my problem.

I've been searching a solut开发者_运维问答ion for this problem but i couldn't have one. By the way i can't understand the reason of my problem.

The problem is:

My web application has a login page and gets logged user id from cookie. It worked before but 5-6 days ago because of something changed it didn't worked with IE. Now it doesn't work with any browser.

I can see the cookie in Chrome. When looked with Internet Explorer Developer Tool sometimes the cookie written but still can't read by IE

My web app is on Windows Server 2008 R2 BTW

Set my web.config:

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

Here is my SetCookie code

<!-- 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);

And this GetCookie code

<!-- 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"]);
}

The scenario is:

trying to log in

SetCookie method triggered

End of SetCookie method there are two cookies "cookieName" and "ASP.NET SessionId"

GetCookie method triggered

There is only "ASP.NET SessionId" and session value still same

Thanks for any help.


My problem solved. Changed my code to this

            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);
            }


This one had me stumped. But managed to solve it as follows. So basically setting the expiry as part of the initialiser does not work. Setting it after adding the cookie to the response object works!

Asp.net HttpCookie Read/Write problem

0

精彩评论

暂无评论...
验证码 换一张
取 消