WebClient Does not automatically redirect

Roman Ratskey picture Roman Ratskey · Oct 23, 2012 · Viewed 20.3k times · Source

When logging the login process using Firebug i see that it is like this

POST //The normal post request
GET //Automatically made after the login
GET //Automatically made after the login
GET //Automatically made after the login

When making a post request using my code below it did not make the automatic GET requests that the browsers is doing.

MY WebClient Handler

using System;
using System.Net;

namespace Test
{
    class HttpHandler : WebClient
    {
        private CookieContainer _mContainer = new CookieContainer();

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = _mContainer;
            }
            return request;
        }

        protected override WebResponse GetWebResponse(WebRequest request)
        {
            var response = base.GetWebResponse(request);
            if (response is HttpWebResponse)
                _mContainer.Add((response as HttpWebResponse).Cookies);
            return response;
        }

        public void ClearCookies()
        {
            _mContainer = new CookieContainer();
        }
    }
}

Using Code

private static async Task<byte[]> LoginAsync(string username, string password)
{
    var postData = new NameValueCollection();
    var uri = new Uri(string.Format("http://{0}/", ServerName));

    postData.Add("name", username);
    postData.Add("password", password);

    return await HttpHandler.UploadValuesTaskAsync(uri, postData);
}

When trying to track the connection of my application it is only doing the POST Request and not the rest of GET requests. [THAT ARE MADE AUTOMATICALLY IN THE BROWSER]

Answer

Dima Nych picture Dima Nych · Oct 24, 2012

Try adding

request.AllowAutoRedirect = true;

right under the

var request = base.GetWebRequest(address);

It solved some similar problems for me, even though AllowAutoRedirect is supposed to be true by default.