silverlight – HttpWebRequest.EndGetResponse在Windows Phone 7中抛出NotSupportedException异常

silverlight – HttpWebRequest.EndGetResponse在Windows Phone 7中抛出NotSupportedException异常,第1张

概述在Silverlight- Windows Phone 7项目中,我正在创建一个HttpWebRequest,获取RequestStream,写入Stream并尝试获取响应,但是我总是得到NotSupportedException: “System.Net.Browser.OHWRAsyncResult.AsyncWaitHandle抛出了一个”System.NotSupportedExcepti 在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;}@H_301_15@  

}

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

解决方法 当调用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);}@H_301_15@  

在尝试从Web服务器获取响应之前,使用块将确保流已关闭.

总结

以上是内存溢出为你收集整理的silverlight – HttpWebRequest.EndGetResponse在Windows Phone 7中抛出NotSupportedException异常全部内容,希望文章能够帮你解决silverlight – HttpWebRequest.EndGetResponse在Windows Phone 7中抛出NotSupportedException异常所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1002040.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存