我有一个在远程服务器上运行的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()
答案 0 :(得分:7)
原来我需要在服务域的根目录中添加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>
答案 1 :(得分:1)
根据this answer,Silverlight(浏览器内)尊重您请求数据的服务器的cross-domain policy。由于它是您自己的Web服务,因此您可以将crossdomain.xml
文件添加到应用程序的根目录,以允许外部域发出跨域请求(this answer)。