C# Sending cookie in an HttpWebRequest which is redirected
- by Nir
I'm looking for a way to work with an API which requires login, and then redirects to another URL.
The thing is that so far I've only come up with a way to make 2 Http Requests for each action I want to do: first, get cookie with AllowRedirect=false, then get the actual URI and do a second request with the cookie:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string redirectedUrl = response.Headers["Location"];
if (!String.IsNullOrEmpty(redirectedUrl))
{
redirectedUrl = "http://www.ApiUrlComesHere.com/" + redirectedUrl;
HttpWebRequest authenticatedRequest = (HttpWebRequest)WebRequest.Create(redirectedUrl);
authenticatedRequest.Headers["Cookie"] = response.Headers["Set-Cookie"];
response = (HttpWebResponse)request.GetResponse();
}
It seems terribly inefficient. Is there another way?
Thanks!