I am writing a small silverlight app just to try silverlight. My idea is to make a small app that checks if websites are online. It works by the user inputting a URL and my app checks it uptime every 5 minutes.
But when ever I do a webrequest I get the security exception below. Reading http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(VS.95).aspx it seems to indicate that silverlight doesn’t allow crossdomain connection. So is there no way to make my idea work in silverlight?
Example code:
WebRequest testHTTP = null;
try
{
testHTTP = WebRequest.Create(serverToCheck);
}
catch (UriFormatException ufe)
{
try
{
testHTTP = WebRequest.Create("http://" + serverToCheck);
}
catch (UriFormatException ufe1)
{
MessageBox.Show("Invalid server address");
}
}
if (testHTTP != null)
{
testHTTP.BeginGetResponse(new AsyncCallback(doCheck), testHTTP);
}
void doCheck(IAsyncResult a)
{
try
{
HttpWebRequest req = (HttpWebRequest)a.AsyncState;
HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(a);
Dispatcher.BeginInvoke(() => HTTPStatus.Content = "OK");
}
catch (Exception ex)
{
//handle exception
}
}
Exception:
{System.Security.SecurityException —> System.Security.SecurityException: Security error.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.b__4(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.b__0(Object sendState)
— End of inner exception stack trace —
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at monitor.Home.doCheck(IAsyncResult a)}
You can’t override the cross domain policy of the server in Silverlight 3. In Silverlight 4 you can with a trusted “out of browser” application.
Your best bet is to create a service that runs on the same domain as the one hosting the Silverlight application and have it do the checks.