[英]How can I get System.Net.Http.HttpClient to not follow 302 redirects?
Using HttpClient from NuGet . 使用NuGet的HttpClient 。
The app sends a post with client.PostAsync(). 该应用程序使用client.PostAsync()发送帖子。 I'd like it to NOT follow 302 redirects.
我希望它不要遵循302重定向。
how? 怎么样?
I figure I can just set AllowAutoRedirect
as described in this answer . 我想我可以按照这个答案中的描述设置
AllowAutoRedirect
。
But how do I get the HttpWebRequest
used within a PostAsync() call? 但是如何在PostAsync()调用中使用
HttpWebRequest
呢?
One of the overloads of the HttpClient
constructor takes a WebRequestHandler
argument. HttpClient
构造函数的一个重载采用WebRequestHandler
参数。 The HttpClient
class uses this WebRequestHandler
for sending requests. HttpClient
类使用此WebRequestHandler
发送请求。
The WebRequestHandler
class provides a property called AllowAutoRedirect
to configure the redirect behaviour. WebRequestHandler
类提供了一个名为AllowAutoRedirect
的属性来配置重定向行为。 Setting this property to false instructs the HttpClient
to not follow redirect responses. 将此属性设置为false会指示
HttpClient
不遵循重定向响应。
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");
To add to Hans' answer: 添加汉斯的回答:
WebRequestHandler derives from HttpClientHandler but adds properties that generally only are available on full .NET.
WebRequestHandler派生自HttpClientHandler,但添加了通常仅在完整.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.
WebRequestHandler不包含在System.Net.Http DLL中,而是包含在System.Net.Http.WebRequest DLL中,因此您必须明确地将其作为引用包含在内以便查看它。 Otherwise it won't show up.
否则它不会出现。
You can just spring for HttpClientHandler if you don't want to add new DLLs: 如果你不想添加新的DLL,你可以为HttpClientHandler加入:
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.AllowAutoRedirect = false;
Reference: https://blogs.msdn.microsoft.com/henrikn/2012/08/07/httpclient-httpclienthandler-and-webrequesthandler-explained/ 参考: https : //blogs.msdn.microsoft.com/henrikn/2012/08/07/httpclient-httpclienthandler-and-webrequesthandler-explained/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.