Using WebRequest and WebResponse, I’m able to post login information to an external site and receive the cookie in Response.Cookies and in my CookieContainer. I know this is working because in the same procedure, I can request a different page and not be redirected to the login page. This cookie is what allows me to stay on the site without logging in with each page view.
I’m now trying to add the cookie to the client’s browser using Response.Cookies.Add(httpCookie);
However, it’s only persisting until the end of the procedure. Reload the page, and the cookie is no longer available.
What am I doing wrong?
The cookies you receive from a
WebResponsefrom an external site cannot be passed onto your own client’s browser. This is because of the inherent security limitations of the cookie model: browsers do not support having one domain set cookies for another domain.This may appear to work until the end of the current request since you are just reading from the
HttpCookieCollectionwhich you just added the cookie to. This collection will persist until the current HTTP request ends.However, to be honest, I’m not sure how you’re able to get this far at all since the the
System.Net.HttpWebResponseandCookieContaineruseSystem.Net.Cookie, while theResponse.Cookiescollection usesSystem.Web.HttpCookie.Anyway, your best bet here is probably to store the value of the cookie you got in the
WebResponseinto your own cookie that you send to the browser. Then, on future requests, read your own cookie, construct a newCookiefor the external site, and add it to theCookieContainermanually.Here is some pseudocode, assuming that the cookie the external site is looking for is named “sessionKey” and we use “myCookie” for the name the cookie we send to our client’s browser: