NotSupportedException when calling EndGetResponse in Silverlight

Share on:

This one had me stumped for a little while today. I was using a WebRequest in a Silverlight 4 application to post some data to an API endpoint, and whenever I called EndGetResponse, a NotSupportedException was thrown.

To help illustrate the problem, here’s a mock-up of the code:

 1
 2using System;
 3using System.Net;
 4using System.Windows.Controls;
 5
 6namespace SilverlightApplication1
 7{
 8    public partial class MainPage : UserControl
 9    {
10        public MainPage()
11        {
12            InitializeComponent();
13
14            var request = (HttpWebRequest)WebRequest.Create("http://myapi.com");
15            request.Method = "POST";
16
17            var myPostData = new byte[10];
18            request.ContentLength = myPostData.Length;
19
20            request.BeginGetRequestStream(
21                a =>
22                {
23                    var stream = request.EndGetRequestStream(a);
24                    stream.Write(myPostData, 0, myPostData.Length);
25                    request.BeginGetResponse(this.GetResponse, request);
26                },
27                null);
28        }
29
30        private void GetResponse(IAsyncResult ar)
31        {
32            var request = (HttpWebRequest)ar.AsyncState;
33            var response = request.EndGetResponse(ar);
34            
35            // Get data from the response stream, etc.
36        }
37    }
38}

After a brief spell of head-scratching, I got to the root of the problem: the request stream wasn’t being closed before the call to EndGetResponse. This meant that as far as the WebRequest was concerned, it was still sending data to the server when I tried to get the response. A NotSupportedException is probably not the most appropriate exception to be thrown in this situation, but there you go.

The fix is simple - either close the request stream or, even better, put it in a using statement to make sure it gets closed off. So lines 22 and 23 become:

1
2using (var stream = request.EndGetRequestStream(a))
3{
4    stream.Write(myPostData, 0, myPostData.Length);
5}

As a side note, I’m usually pretty strict about wrapping objects that implement IDisposable in a using statement - this is a good reminder why that is!