在Silverlight-Windows Phone 7项目中,我正在创建HttpWebRequest,获取RequestStream,将某些内容写入Stream中并尝试获取响应,但是我始终会收到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;
}

}

有人知道这段代码有什么问题吗?

最佳答案

如果在调用NotSupportedException之前未关闭请求流,则可以抛出EndGetResponse。尝试获取响应时,WebRequest流仍处于打开状态,并且正在将数据发送到服务器。由于流实现了IDisposable接口(interface),因此一个简单的解决方案是使用请求流将您的代码包装在using块中:

private void BeginRequest(IAsyncResult ar)
{
    using (Stream stream = request.EndGetRequestStream(ar))
    {
        //write to stream in here.
    }
    state.Request.BeginGetResponse(
        new AsyncCallback(BeginResponse), state);
}

using块将确保在尝试从Web服务器获取响应之前关闭流。

10-08 12:16