0

在 HttpClientHandler 中具有 AllowAutoRedirect 属性,但在为 WindowsPhone 构建应用程序时会抛出异常:

此平台不支持 HttpClientHandler.AllowAutoRedirect。请在使用 HttpClientHandler.AllowAutoRedirect 之前检查 HttpClientHandler.SupportsRedirectConfiguration。

我真的很想阻止自动重定向。我尝试使用 HttpWebRequest:

    var client = (HttpWebRequest) WebRequest.Create(connectionUrl);
client.Headers["AllowAutoRedirect"] = "false";
client.Method = "GET";
client.Headers["UserAgent"] = @"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31";
client.ContentType = "application/json";
client.Headers["ContentLength"] = client.ToString().Length.ToString();
client.BeginGetResponse(Callback, client);
private void Callback(IAsyncResult ar)
{
var requestState =(HttpWebRequest) ar.AsyncState;
using (var postStream = requestState.EndGetRequestStream(ar))
{}
}

此代码在 EndGetRequestStream 上引发异常:“值不在预期范围内”期待您的帮助。

4

2 回答 2

1

我认为您收到了 ,ArgumentException: Value does not fall within the expected range因为您BeginGetResponse()在客户端上启动 a ,然后EndGetRequestStream()在您的回调中执行 a ,而不是您应该调用EndGetResponse(). 设置AllowAutoRedirect工作正常,您只需要修复您的代码。试试这个:

  var client = (HttpWebRequest)WebRequest.Create(connectionUrl);
  client.AllowAutoRedirect = false;
  client.Method = "GET";
  client.BeginGetResponse(Callback, client);

  private void Callback(IAsyncResult ar) {
      var state = (HttpWebRequest)ar.AsyncState;
      using (var response = state.EndGetResponse(ar)) {
          var streamResponse = response.GetResponseStream();
          var streamRead = new StreamReader(streamResponse);
          var responseString = streamRead.ReadToEnd();
      }
  }
于 2013-05-08T16:59:34.313 回答
0

为什么不将 HttpClient 与 HttpClientHandler 一起使用?

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

// Create an HttpClient using the HttpClientHandler
HttpClient client = new HttpClient(clientHandler);

更多信息:http: //blogs.msdn.com/b/henrikn/archive/2012/08/07/httpclient-httpclienthandler-and-httpwebrequesthandler.aspx

于 2015-04-25T11:50:23.650 回答