2013-05-08 47 views
0

在HttpClientHandler已經propertie AllowAutoRedirect,但對WindowsPhone的拋出異常構建應用程序: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:「值沒有在預期範圍內」 我期待着您的幫助。

回答

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(); 
     } 
    } 
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

+0

夥計,我在兩年前問它。但無論如何,謝謝你的幫助 – starostin13 2015-05-20 14:10:58