How can I get System.Net.Http.HttpClient to not follow 302 redirects?

后端 未结 2 1320
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 04:41

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

2条回答
  •  没有蜡笔的小新
    2020-12-06 05:05

    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 response = httpClient.GetAsync("http://www.google.com");
    

提交回复
热议问题