SecurityException While Accessing WCF Service

I am just getting started with Silverlight.  For my first application, I wrote a simple form that interacts with a WCF service for database access.

The first time I tried to access the WCF service from the Silverlight application I got a SecurityException.  The error message that the exception gave was long and rambling and mentioned things like “cross domain access” and other fairly meaningless bafflegab.  I spent a lot of time Googling for solutions to this problem and the results all had to do with tweaking the IIS security settings, which are irrelevant when using Visual Studio’s internal web server.

I finally stumbled upon the solution to the problem myself.  Visual Studio’s internal web server grabs a more-or-less random port number each time it starts.  This means that the port number can, and does, change from time to time.  So, suppose the internal web server was using port number 10000 at the time you added the service reference to your Silverlight project.  Unless you take steps to change it, this becomes the port number used to interact with the service.  All well and good.  But the next time you start the internal web server it may choose to use port number 20000.   Now your service is no longer where your Silverlight application expects to find it.  Rather than giving a meaningful error, like “Hey stupid I can’t find the service at that address” the .Net framework gives you a completely misleading SecurityException.

To fix this all you have to do is open the ServiceReferences.ClientConfig file in your Silverlight project and change the service URI to reference the port currently being used by the internal web server.  You can find the port number by right clicking the internal web server’s icon on the task bar and selecting  Show Details.

This is a monumental pain in the butt.  If you are developing your Silverlight application as part of a web project you can force Visual Studio’s internal web server to always use a specific port number.  To do this, click in the web project in Solution Explorer and press F4 to display the properties pane.  Change the Use dynamic ports property to False and change the Port number property to the port number that you want to use.  You need to be certain that the port number that you select in not in used by something else or you will get errors when you try to start the internal web server.

Leave a Reply