Reputation: 15423
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?
Upvotes: 1
Views: 6892
Reputation: 21455
The cookies you receive from a WebResponse
from 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 HttpCookieCollection
which 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.HttpWebResponse
and CookieContainer
use System.Net.Cookie
, while the Response.Cookies
collection uses System.Web.HttpCookie
.
Anyway, your best bet here is probably to store the value of the cookie you got in the WebResponse
into your own cookie that you send to the browser. Then, on future requests, read your own cookie, construct a new Cookie
for the external site, and add it to the CookieContainer
manually.
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:
public ActionResult MyAction()
{
var container = new CookieContainer();
if (Request.Cookies["myCookie"] != null)
{
// browser has passed in "myCookie".
// use this to create the "sessionKey" cookie to send.
var cookie = new System.Net.Cookie("sessionKey",
Request.Cookies["myCookie"].Value, "/", "external-site.com");
container.Add(cookie);
}
HttpWebRequest request;
HttpWebResponse response;
// initialize the request.
// ...
// make sure we're using our cookie container.
request.CookieContainer = container;
// execute the request and get the response.
response = request.GetResponse();
// send a cookie, "myCookie", to the browser.
// it will contain the value of the "sessionKey" cookie.
Response.Cookies["myCookie"].Value = response.Cookies["sessionKey"].Value;
}
Upvotes: 3