您的位置:首页 > 其它

Silverlight学习笔记——读取宿主web.config

2014-09-18 20:42 387 查看


本文将建立一个silverlight项目中读取宿主网站web.config配置文件数据的简单实例,以下是详细步骤:

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),在这里添加一条我们的键值对吧,键为InitParams,值为我们先前添加在web.config中的内容
<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" />
<%--添加参数[InitParams]传递到客户端的sl程序中 --%>
<param name="InitParams" value='WcfServiceAddress=<%= System.Configuration.ConfigurationManager.AppSettings["WcfServiceAddress"] %>' />
<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>


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;


转自:/article/5133791.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: