Monday, September 20, 2010
Introducing BlogoRadio!
Tuesday, September 14, 2010
Using WCF Services with Silverlight in a Cross Domain Way
One of the useful features available for developingSilverlight applications is its ability to interact with server side datathrough the use of a conduit such as Windows Communication Foundation (WCF)services. Visual studio enablesapplication developers to easily connect to a service using “Project->Add ServiceReference”, then providing the address for the service. The various operations and data structuresmade public by that service are then exposed in the solution and can be viewedusing the object browser. When accessingthe service from a different domain, as in trying to access the service fromwithin a development running on the local machine and the service is notrunning on localhost, there is the potential for your Silverlight applicationto throw an exception if the server hosting your service has not explicitlyenabled a cross-domain access policy. Ifthis happens, the application exception may look something like this:
An error occurred while trying to make a request to URI 'http://kenwatts.net/Service.svc'. This could be due to attempting toaccess a service in a cross-domain way without a proper cross-domain policy inplace, or a policy that is unsuitable for SOAP services. You may need tocontact the owner of the service to publish a cross-domain policy file and toensure it allows SOAP-related HTTP headers to be sent. This error may also becaused by using internal types in the web service proxy without using theInternalsVisibleToAttribute attribute. Please see the inner exception for moredetails.
In order to get around this issue, a file named “clientaccesspolicy.xml”needs to be added to the root of the server where the service is running. This file can have the following contents toenable services from any subdirectory:
<?xml version="1.0"encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-fromhttp-request-headers="*">
<domain uri="*" />
</allow-from>
<grant-to>
<resourcepath="/" include-subpaths="true" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
It’s important to point out that this file needs to belocated in the root of the server where the service is hosted. So if the Silverlight application is tryingto access this service:
http://www.mydomain.com/MyWcfService/MyWcfService.svc
Then the file “clientaccesspolicy.xml” needs to be locatedhere:
http://www.mydomain.com/clientaccesspolicy.xml
By enabling the cross-domain policy in this way, developerscan avoid this cross-domain exception when deploying a Silverlight applicationon a server that is different from the server hosting the data providingservice.
For more information about cross-domain access policiesrelated to Silverlight and WCF, check these links: