在Silverlight-
Windows Phone 7项目中,我正在创建一个HttpWebRequest,获取RequestStream,写入Stream并尝试获取响应,但是我总是得到NotSupportedException:
“System.Net.Browser.OHWRAsyncResult.AsyncWaitHandle抛出了一个”System.NotSupportedException“类型的异常
“System.Net.Browser.OHWRAsyncResult.AsyncWaitHandle抛出了一个”System.NotSupportedException“类型的异常
public class HttpUploadHelper { private HttpWebRequest request; private RequestState state = new RequestState(); public HttpUploadHelper(string url) { this.request = WebRequest.Create(url) as HttpWebRequest; state.Request = request; } public void Execute() { request.Method = "POST"; this.request.BeginGetRequestStream( new AsyncCallback(BeginRequest),state); } private void BeginRequest(IAsyncResult ar) { Stream stream = state.Request.EndGetRequestStream(ar); state.Request.BeginGetResponse( new AsyncCallback(BeginResponse),state); } private void BeginResponse(IAsyncResult ar) { // BOOM: NotSupportedException was unhandled; // {System.Net.Browser.OHWRAsyncResult} // AsyncWaitHandle = 'ar.AsyncWaitHandle' threw an // exception of type 'System.NotSupportedException' HttpWebResponse response = state.Request.EndGetResponse(ar) as HttpWebResponse; Debug.WriteLine(response.StatusCode); } } public class RequestState { public WebRequest Request; }
}
有人知道这段代码有什么问题吗?
解决方法
当调用EndGetResponse之前请求流未关闭时,可以抛出NotSupportedException异常.当您尝试获取响应时,WebRequest流仍然打开并将数据发送到服务器.由于流实现了IDisposable接口,一个简单的解决方案是使用使用块中的请求流来包装您的代码:
private void BeginRequest(IAsyncResult ar) { using (Stream stream = request.EndGetRequestStream(ar)) { //write to stream in here. } state.Request.BeginGetResponse( new AsyncCallback(BeginResponse),state); }