silverlight程序會被下載到客戶端去執行,所以沒法操作到服務端的配置文件,導致了我們在部署時遇到很多問題,(例如:silverlight程序和wcf的通訊地址,在發佈時,我們的開發環境配置將可能不再適用,需要根據服務端實際情況重新配置),如果可以讓silverlight程序讀取到web.config中的配置數據,將會大大簡化我們的部署工作,那麼有沒有辦法可以達到這樣的效果呢,答案是肯定的。
1.首先在宿主網站的web.config中,添加我們要傳遞給silverlight程序的鍵值對
<?xml version="1.0" encoding="utf-8"?> <!-- 有關如何配置 ASP.NET 應用程序的詳細消息,請訪問 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <appSettings> <add key="WcfServiceAddress" value="http://localhost:9090/Service.svc"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> </configuration>
本例中添加了一個[wcfServiceAddress]的值
2.打開vs爲我們在宿主網站中自動生成的訪問頁面(*.aspx,*.html),找到已經自動添加的一些鍵值對如下
<body> <form id="form1" runat="server" style="height: 100%"> <div id="silverlightControlHost"> <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="ClientBin/com.higo.ui.sl.xap" /> <param name="onError" value="onSilverlightError" /> <param name="background" value="white" /> <param name="minRuntimeVersion" value="4.0.50826.0" /> <param name="autoUpgrade" value="true" /> <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration: none"> <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="獲取 Microsoft Silverlight" style="border-style: none" /> </a> </object> <iframe id="_sl_historyFrame" style="visibility: hidden; height: 0px; width: 0px; border: 0px"></iframe> </div> </form> </body>
那麼就在這裏添加一條我們的鍵值對吧,鍵爲InitParams,值爲我們先前添加在web.config中的內容
<%--添加參數[InitParams]傳遞到客戶端的sl程序中 --%> <param name="InitParams" value='WcfServiceAddress=<%= System.Configuration.ConfigurationManager.AppSettings["WcfServiceAddress"] %>' />
3.宿主網站的修改完畢,接下來修改一下我們的silverlight程序,打開對應的App.xml.cs,在啓動事件裏添加獲取我們的鍵值對,並添加到程序資源中去,方便我們的使用
private void Application_Startup(object sender, StartupEventArgs e) { //將讀取到的WCF地址保存到資源中。 var slServicePath = e.InitParams["WcfServiceAddress"]; Application.Current.Resources.Add("WcfServiceAddress", slServicePath); this.RootVisual = new MainPage(); }
ok,new一個頁面來做舞臺show一下效果吧
前端:
<Grid x:Name="LayoutRoot"> <ScrollViewer x:Name="PageScrollViewer" Style="{StaticResource PageScrollViewerStyle}"> <StackPanel x:Name="ContentStackPanel"> <TextBlock x:Name="ConfigText" Style="{StaticResource ContentTextStyle}"/> </StackPanel> </ScrollViewer> </Grid>
後臺:
this.ConfigText.Text = Application.Current.Resources["WcfServiceAddress"] as string;