I recently was working on a Silverlight 2 project and needed to "phone home" from the .xap back to the server of origin to get a text file from the server. It wasn't completely obvious how to do this at first, so I figured I'd share the code I wrote if others need to do something similar. Note a couple things:
- You'll need to add a reference to System.Net.dll and using statements for System.Net and System.IO.
- The ASP.NET WebDev server used for development will run the project on a random port. You can change this behavior so you have a consistent port number. Click on the project node in Solution Explorer and open the properties window (press F4). Change the “Use dynamic ports” property from True to False and edit the port number.
- If you try to go to a server other than the server of origin, you'll most likely run into cross site scripting issues.
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
//you may need to change this path depending on your web server
WebRequest request = WebRequest.Create(new Uri("http://localhost:4386/io_web/textfile.txt"));
request.Method = "GET";
request.ContentType = "text/plain";
request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
}
void ResponseReady(IAsyncResult asyncResult)
{
WebRequest request = asyncResult.AsyncState as WebRequest;
using (WebResponse response = request.EndGetResponse(asyncResult))
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
string s = reader.ReadLine();
System.Diagnostics.Debug.WriteLine(s);
}
}
}
}