SecurityException from using HttpWebRequest cross-domain in Silverlight 4
I'm trying to write a function in my Silverlight app that requests a particular page that doesn't exist on the same domain as where my Silverlight app is hosted.
For example:
- Silverlight App: http://www.mysilverlightsite.com/
- Target Page: http://www.mysite.com/MyPage.aspx
However, this generates a 'SecurityException':
{System.Security.SecurityException: Security error. at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) ...}
From what I understand, this is related to cross-domain requests being restricted, and found some posts that mentioned that this article (http://msdn.microsoft.com/en-us/library/cc197955(VS.95).aspx) might be related.
Here's my code:
public static void CheckPageContentsAsync(CheckPageContentsCallback callback, DependencyObject uiObject)
{
bool result = false;
try
{
HttpWebRequest request = WebRequest.CreateHttp("http://www.mysite.com/MyPage.aspx");
request.BeginGe开发者_JAVA技巧tResponse((asyncHandle) =>
{
try
{
uiObject.Dispatcher.BeginInvoke(new VoidDelegate(() =>
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncHandle);
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string content = sr.ReadToEnd();
if (content.Contains("Value"))
{
result = true;
}
if (callback != null)
{
callback.Invoke(result);
}
}
}), null);
}
catch (Exception excep)
{
throw new Exception("Failed to process response.", excep);
}
}, null);
}
catch(Exception excep2)
{
throw new Exception("Failed to generate request.", excep2);
}
}
Haven't been able to make much sense of the applicability of the "clientaccesspolicy.xml" or "crossdomain.xml" files as a solution.
Can anyone explain clearly how I modify my app, or the web server I'm requesting from, to resolve this issue?
I use to copy this file in the root of my app:
<cross-domain-policy>
<allow-access-from domain="*.*" headers="SOAPAction"/>
<allow-http-request-headers-from domain="*.*" headers="SOAPAction"/>
<site-control permitted-cross-domain-policies="master-only"/>
</cross-domain-policy>
Name it crossdomain.xml.
精彩评论