Saturday, April 12, 2008

Silverlight 2.0 Beta1 CrossDomain Issues

Preparing for my upcoming "What's New with ASP.NET 3.5 Extensions" presentation at the Central Ohio Day of .Net, I ran into a roadblock with my simple Silverlight demo.

I have a Silverlight application calling an ASP.Net Web Service (traditional ASMX). The Silverlight application is hosted on an ASPX page served up in an ASP.Net Web Application.

I kept receiving a mix of the following two errors:

An exception of type 'System.ServiceModel.CommunicationException' occurred in System.ServiceModel.dll but was not handled in user code

Additional information: [CrossDomainError]

---------------------------------------------------------------

An exception of type 'System.ServiceModel.ProtocolException' occurred in System.ServiceModel.dll but was not handled in user code

Additional information: [UnexpectedHttpResponseCode]
Arguments:Not Found

Essentially, this is saying, "hey this control/page you're browsing on safesite.com is trying to interact with something over on unsafesite.com...and we're preventing it". Good for security, bad for demos.

Originally, when creating my Silverlight application, I chose the "Generate an HTML test page to host Silverlight within this project" option instead of creating a new web application. Bad idea. You'll always experience this cross domain issue using the HTML hosting page while calling a backend service. I quickly switched to a web application.

The easiest fix for me was to switch the web site and web service from using Cassini  localhost with dynamic ports to the machine name and named virtual directories.

Here's my original properties on the web service project:

image

I switched it to:

image

The fine folks at Microsoft even provided a helpful "Create Virtual Directory" button.

Within my Silverlight project, I also needed to update the Service Reference (orginal):

image

I switched it to:

image

After you Configure Service Reference (above), make sure you Update Service Reference (below) to update the configuration code built for you by Visual Studio:

image

Despite the Silverlight 2.0 Beta1 recent release, there is much traffic about this issue in the forums and on blogs. It's actually nothing new. I ran into this issue with Flash a while back. Another, more production-ready solution is to leverage a policy file indicating to the object (Silverlight, in this case) that it's ok to interact with a particular service on some other domain. This is a file named crossdomain.xml and/or clientaccesspolicy.xml. More information at "Some tips on cross-domain calls" and "How to: Make a Service Available Across Domain Boundaries".

RELATED

Silverlight 2.0 and WCF

Silverlight Forums CrossDomainError

1 comment:

Kevin said...

Intersting post and good to know to watch out for this.