编程语言
首页 > 编程语言> > c# – Silverlight HttpWebRequest SecurityException

c# – Silverlight HttpWebRequest SecurityException

作者:互联网

问题

我有一个在远程服务器上运行的restful Web服务.我已经制作了一个使用它的WP7应用程序,所以我知道它有效.我正在将应用程序移植到Silverlight Web应用程序并遇到问题.

我已经包含了代码的简化版本以及引发的错误. EndGetResponse方法抛出错误.

随意询问更多信息.我一直在寻找解决方案,但没有发现任何有效或真正适用于我的问题的东西.看起来像这样简单的代码,它在WP7版本上运行得很好.任何帮助将不胜感激.

代码

void SendRequest() {
    string url = "http://some-example-restful-service:5600/locations/data/all";
    HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);

    request.Method = "POST";
    request.ContentType = "application/json; charset=utf-8";

    request.BeginGetResponse(new AsyncCallback(RequestCallback), request);
}

public static void RequestCallback(IAsyncResult asyncResult) {
    HttpWebRequest request = (HttpWebRequest) asyncResult.AsyncState;
    HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(asyncResult);

    //Parse JSON object

    response.Close();

    //Dispatch result back to GUI thread
}

错误

SecurityException未被用户代码处理

System.Security.SecurityException:安全性错误.

at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>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 ServieTest.MainPage.RequestCallback(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassd.<InvokeGetResponseCallback>b__b(Object state2)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

解决方法:

结果我需要在服务域的根目录上添加clientaccesspolicy.xml文件.

以下是文件内容应该是:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
    <cross-domain-access>
        <policy>
            <allow-from http-request-headers="*">
                <domain uri="*"/>
            </allow-from>
            <grant-to>
                <resource path="/" include-subpaths="true"/>
            </grant-to>
        </policy>
    </cross-domain-access>
</access-policy> 

标签:c,web-applications,httpwebrequest,silverlight,silverlight-4-0
来源: https://codeday.me/bug/20190610/1209075.html