Tuesday, February 15, 2011

Accessing WCF Services from Other Domains

WCFAccessing Services from Other Domains

In the previous example, the web service was on the same domain as your Silverlight application. What if
you want to call a service that is on a different domain?
In fact, as a best practice, it is preferred to have your web services stored on a domain separate from
your web application. Even for applications where you control both the web service and the Silverlight
application, you may be dealing with different domains.
If you attempt to access a service from a different domain in Silverlight, you will notice that it fails.
This is because, by default, a Silverlight application cannot call services that are on a different domain,
unless it is permitted to do so by the service host. In order for Silverlight to determine if it has permission
to access a service on a certain domain, it will look for one of two files in the root of the target domain:
clientaccesspolicy.xml or crossdomain.xml.
First, Silverlight will look for a file named clientaccesspolicy.xml in the domain’s root. This is
Silverlight’s client-access policy file. If you are publishing your own services that you want to be
accessible by Silverlight applications, this is the file that you want to use, as it provides the most options
for Silverlight application policy permissions. The following is a sample clientaccesspolicy.xml file:

<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>

The important elements are <allow-from> and <grant-to>. The <allow-from> element defines which
domains are permitted to access the resources specified in the <grant-to> element.
If Silverlight cannot find a clientaccesspolicy.xml file at the root of the domain from which you are
attempting to access a service, it will then look for a file named crossdomain.xml in the root. This is the
XML policy file that has been used to provide access for Flash applications to access cross-domain
services, and Silverlight supports this file as well. The following is an example of a crossdomain.xml file:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy
SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

Again, even though Silverlight supports crossdomain.xml, using clientaccesspolicy.xml for
Silverlight applications is the preferred and best practice.

No comments: