31

Using HttpClient from NuGet.

The app sends a post with client.PostAsync(). I'd like it to NOT follow 302 redirects.

how?

I figure I can just set AllowAutoRedirect as described in this answer.

But how do I get the HttpWebRequest used within a PostAsync() call?

Community
  • 1
  • 1
Cheeso
  • 189,189
  • 101
  • 473
  • 713

2 Answers2

47

One of the overloads of the HttpClient constructor takes a WebRequestHandler argument. The HttpClient class uses this WebRequestHandler for sending requests.

The WebRequestHandler class provides a property called AllowAutoRedirect to configure the redirect behaviour. Setting this property to false instructs the HttpClient to not follow redirect responses.

Here is a small code sample:

WebRequestHandler webRequestHandler = new WebRequestHandler();

webRequestHandler.AllowAutoRedirect = false;

HttpClient httpClient = new HttpClient(webRequestHandler);

// Send a request using GetAsync or PostAsync

Task<HttpResponseMessage> response = httpClient.GetAsync("http://www.google.com");
Hans
  • 12,902
  • 2
  • 57
  • 60
  • 1
    ok thanks. That means I cannot specify 302-following behavior per call, correct? It is per-handler, which implies, I guess, per-instance of HttpClient. Yes? – Cheeso May 05 '12 at 19:18
  • 2
    Yes, it's per instance of the HttpClient. If you try to modify the AllowAutoRedirect property between two calls you will get an exception. – Hans May 05 '12 at 20:44
16

To add to Hans' answer:

WebRequestHandler derives from HttpClientHandler but adds properties that generally only are available on full .NET. The WebRequestHandler is not included in the System.Net.Http DLL but rather in System.Net.Http.WebRequest DLL so you have to explicitly include that as a reference in order to see it. Otherwise it won’t show up.

You can just spring for HttpClientHandler if you don't want to add new DLLs:

    HttpClientHandler clientHandler = new HttpClientHandler();
    clientHandler.AllowAutoRedirect = false;

Reference: https://blogs.msdn.microsoft.com/henrikn/2012/08/07/httpclient-httpclienthandler-and-webrequesthandler-explained/

rothschild86
  • 1,433
  • 16
  • 22