windowsPhone中的AllowAutoRedirect

时间:2013-05-08 16:10:43

标签: c# httpwebrequest windows-phone-8 httpclient

在HttpClientHandler中有属性AllowAutoRedirect,但是对于WindowsPhone的构建应用程序抛出异常:

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

我真的想阻止autoredirect。 我试图使用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上的异常:“值不在预期范围内” 我期待着你的帮助。

2 个答案:

答案 0 :(得分:1)

我认为您收到的是ArgumentException: Value does not fall within the expected range,因为您在客户端上发起BeginGetResponse(),但在回调中执行了EndGetRequestStream(),而您应该拨打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();
      }
  }

答案 1 :(得分: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