It is a very common ASP.NET scenario to have to read a configuration parameter from web.config. This operation is very easily implemented from ASPX using Configuratoin.AppSettings. However, this scenario does not work out of the box from a Silverlight application, which doesn’t seem to even have access to web.config.

The reason is simple: a Silverlight application runs on the client side. The XAP -just like the browser- cannot access server resources such as web.config; you cannot, for example, get the site’s configuration file using an URI such as http://www.mysite.com/web.config.

This post demonstrates two workarounds to get the configuration data from your server’s configuration to your XAP.

The first solution is to actually not store configuration data in your web.config file, but to another file which would be made available by IIS like any other network resource. This file could then be downloaded, parsed and interpreted by the XAP.

The second solution, usually simpler to implement, makes use of ASP.NET’s ConfigurationSettings class and passes the web.config values to the Silverlight.InitParameters property. This works as follows:

<script runat="server">

    private void Page_Load()

    {

        var mySetting = ConfigurationSettings.AppSettings["mySetting"];

        mySlPart.InitParameters = string.Format("mySilverlightSetting={0}", mySetting);

    }

</script>

1.      In the ASPX page, read the values from web.config using ConfigurationSettings.AppSettings

2.      Format these values as follows : "arg1=ma valeur,arg2=ma deuxieme valeur"

3.      Assign the formatted string to the your Silverlight control’s InitParameter property

4.      From Silverlight, get the InitParameters values from your Application.Startup handler, in the InitParams property of the event’s argument.

   if (e.InitParams.ContainsKey("mySilverlightSetting"))

      maVariable = e.InitParams["mySilverlightSetting"];

 

SlreadwebconfigEN

The attached application gives a working example of the second solution. Thanks to Regis for giving me something to post about !