C# Sending cookie in an HttpWebRequest which is redirected

Posted by Nir on Stack Overflow See other posts from Stack Overflow or by Nir
Published on 2010-04-25T10:31:16Z Indexed on 2010/04/25 10:33 UTC
Read the original article Hit count: 211

Filed under:
|
|
|

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!

© Stack Overflow or respective owner

Related posts about c#

Related posts about api