Handling Cookies with Redirects and HttpWebRequest

The HttpWebRequest handles redirects automatically. That’s usually a nice feature but it can actually get in the way when the web server is setting cookies in the same response in which it is sending a redirect. For some odd reason the HttpWebRequest object will totally discard cookies that are set with a redirect response. I ran into a problem with this when I was working in some code that interfaced to Google Voice and it was driving me crazy since I didn’t know where the problem was coming from.

Once I figured out what was happening the solution to the problem was simple. The first step is to disable the class’s automatic response to redirect request. When a response is returned from the class it’s necessary to check the response to see if it includes a redirect and if so create a new request. Since a redirect could occur more than once it is necessary to do this in a loop. With each new WebRequest that is created it is necessary to set the CookiesContainer member.

A simplified version of my code looks like the following:

using System.Net;

HttpWebRequest GetNewRequest(string targetUrl) { 
	HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUrl); 
	request.CookieContainer = SessionCookieContainer; 
	request.AllowAutoRedirect = false; 
	return request; 
}
HttpWebRequest request = GetNewRequest(targetUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
while (response.StatusCode == HttpStatusCode.Found)
{
	response.Close(); 
	request = GetNewRequest(response.Headers["Location"]); 
	response = (HttpWebResponse)request.GetResponse();
}
//--At this point the redirected response is ready to be used  

Trying to perform this same thing on the .Net Compact Framework is a little more challenging since it doesn’t support cookies at all. I’ll discuss the solution I used in another post within the next few days.


From the Blog Engine Archives

Posts may contain products with affiliate links. When you make purchases using these links, we receive a small commission at no extra cost to you. Thank you for your support.

Mastodon: @j2inet@masto.ai
Instagram: @j2inet
Facebook: @j2inet
YouTube: @j2inet
Telegram: j2inet
Twitter: @j2inet

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.