Search code examples
c#silverlightwebrequest

Web Requests in C# for SilverLight 2.0


I have been using the following code to obtain a simple web response from Apache 2.2 in SilverLight to no avail.

    private void bDoIt_Click(object sender, RoutedEventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("/silverlight/TestPage2.html"));

        request.Method = "POST";
        request.ContentType = "text/xml";

        request.BeginGetRequestStream(new AsyncCallback(RequestProceed), request);
    }

    private void RequestProceed(IAsyncResult asuncResult)
    {
        HttpWebRequest request = (HttpWebRequest)asuncResult.AsyncState;

        StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asuncResult));
        postDataWriter.Close();

        request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);

    }

    private void ResponceProceed(IAsyncResult asuncResult)
    {
        HttpWebRequest request = (HttpWebRequest)asuncResult.AsyncState;

        HttpWebResponse responce = (HttpWebResponse)request.EndGetResponse(asuncResult);
        StreamReader responceReader = new StreamReader(responce.GetResponseStream());

        string responceString = responceReader.ReadToEnd();

        txtData.Text = responceString;
    }

Does anyone no a better method of doing this?


Solution

  • Have you tried WebClient? This exists on silverlight, and might make life easier. Presumably you'd want UploadStringAsync.

    Also - I believe you need to use and absolute url; if you don't want to hard code (quite reasonably), you can get your host from:

    string url = App.Current.Host.Source.AbsoluteUri;
    

    Then use string / etc methods to make the correct "http://yoursite/whatever/your.page";

    Note that silverlight only allows (IIRC) connections to the host site.