Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequest.EndGetResponse throws a NotSupportedException in Windows Phone 7

in a Silverlight-Windows Phone 7-project I am creating an HttpWebRequest, get the RequestStream, write something into the Stream and try to get the response, but I always get a NotSupportedException: "System.Net.Browser.OHWRAsyncResult.AsyncWaitHandle threw an exception of type 'System.NotSupportedException'

My production code is far more complicated, but I can narrow it down to this small piece of code:

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

}

Does anybody know what is wrong with this code?

like image 234
Arne Janning Avatar asked Nov 12 '10 15:11

Arne Janning


1 Answers

The NotSupportedException can be thrown when the request stream isn't closed before the call to EndGetResponse. The WebRequest stream is still open and sending data to the server when you're attempting to get the response. Since stream implements the IDisposable interface, a simple solution is to wrap your code using the request stream in a using block:

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

The using block will ensure that the stream is closed before you attempt to get the response from the web server.

like image 180
brappleye3 Avatar answered Oct 31 '22 10:10

brappleye3