在Silverlight 4中使用HttpWebRequest跨域的SecurityException

时间:2011-04-01 22:00:14

标签: c# security silverlight-4.0 httpwebrequest cross-domain

我正在尝试在我的Silverlight应用程序中编写一个函数,该函数请求与我的Silverlight应用程序托管位置不同的特定页面。

例如:

但是,这会生成'SecurityException':

  

{System.Security.SecurityException:   安全错误。在   System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult的   asyncResult)at   System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult的   asyncResult)...}

据我了解,这与跨域请求受到限制有关,并发现一些帖子提到了这篇文章(http://msdn.microsoft.com/en-us/library/cc197955(VS.95) ).aspx)可能是相关的。

这是我的代码:

public static void CheckPageContentsAsync(CheckPageContentsCallback callback, DependencyObject uiObject)
{
    bool result = false;
    try
    {
        HttpWebRequest request = WebRequest.CreateHttp("http://www.mysite.com/MyPage.aspx");
        request.BeginGetResponse((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);
    }
}

无法充分了解“clientaccesspolicy.xml”或“c​​rossdomain.xml”文件作为解决方案的适用性。

任何人都可以清楚地解释我如何修改我的应用程序或我要求的网络服务器来解决此问题吗?

1 个答案:

答案 0 :(得分:1)

我用来在我的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>

将其命名为crossdomain.xml。