65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 ASP.NET 的 Web.config 文件配置 Silverlight 3 应用程序

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.43/5 (18投票s)

2010 年 1 月 5 日

CPOL

7分钟阅读

viewsIcon

117683

downloadIcon

1011

本文介绍了一种使用 ASP.NET 的 Web.config 文件配置 Silverlight 3 应用程序的方法。

引言

本文介绍了一种使用 Web.config 文件从 ASP.NET 配置 Silverlight 3 应用程序的方法。

背景

随着 XML Web Services 的出现以及最近 WCF 技术的出现,富 Internet 应用程序(RIA)在 IT 领域越来越受到关注。三个主要的竞争技术代表了 RIA 技术的发展。它们是 Adobe Flex、JAVA Applet 和 Silverlight。Adobe 随处可见,这具有其优势。JAVA Applet 不再像以前那样流行,但其辉煌的过去和清晰的 JAVA 编程环境应该预示着其未来的复兴。与前两者相比,Silverlight 出现得较晚,但其漂亮的 .NET 编程环境和与 WCF 的紧密集成使其成为开发严肃 IT 应用程序的理想平台。我们应该期望这三种技术在未来很长一段时间内共存。在本文中,我们将重点关注 Silverlight,并介绍一种使用 ASP.NET 主机 Web 应用程序中的 Web.config 文件配置 Silverlight 应用程序的方法。

我最近的一个 Silverlight 项目需要与 WCF 服务通信,以便与数据库服务器传输一些业务数据。服务器管理员问我是否可以让他更改托管的 ASP.NET 应用程序的 Web.config 文件来指定 WCF 服务的地址。他非常熟悉支持 IIS 托管的 ASP.NET 应用程序,并且使用 Web.config 文件来配置 IIS 托管的应用程序一直是一项标准做法。通过研究 Silverlight 应用程序如何嵌入到 ASP.NET 页面以及 Silverlight 应用程序的“InitParams”参数,我找到了一种方法。以下是通过一个简单的示例 Visual Studio 解决方案分步介绍此方法。

示例代码使用 Visual Studio 2008 和 Silverlight 3 开发。

在 Visual Studio 2008 中创建 Silverlight 应用程序

要创建 Silverlight 应用程序,您需要在计算机上安装一个版本的 Silverlight Toolkit。我在此示例中使用的版本是 Silverlight 3。安装工具包后,您可以打开 Visual Studio 2008 并创建一个 Silverlight 应用程序,将其命名为“SilverlightConfigurationDemo”。当向导询问您是否要创建主机 Web 应用程序时,请选择“是”,并将此 Web 应用程序的默认名称更改为“SilverlightConfigurationDemoWeb”。按照 Visual Studio 的其余说明进行操作。完成 Silverlight 应用程序的创建后,解决方案资源管理器应如下图所示。

Solution Explorer

Visual Studio 创建了两个项目。一个是 Silverlight 应用程序,另一个是主机 ASP.NET Web 应用程序。Web 应用程序是默认的启动项目。两个项目都被添加到一个名为“SilverlightConfigurationDemo”的 Visual Studio 解决方案中,该名称与 Silverlight 应用程序项目相同。上图显示了解决方案资源管理器中的两个项目。

在托管的 ASP.NET Web 应用程序项目中,您会注意到 Visual Studio 创建了两个文件。它们是“SilverlightConfigurationDemoTestPage.aspx”和“SilverlightConfigurationDemoTestPage.html”。Visual Studio 已经在两个文件中创建了托管 Silverlight 应用程序所需的 HTML、样式和 JavaScript。实际上,我们可以使用任何网页来托管 Silverlight 应用程序。在本文中,正如您稍后将看到的,我们将使用“Default.aspx”。

将配置信息添加到 Web.config 文件

为了演示,我们将以下内容添加到 Web.config 文件中

<appSettings>
 <add key="ApplicationName" value="Silverlight Configuration Demonstration"/>
 <add key="WCFEndPointAddress" value="https:///HelloService/MyService" />
 <add key="AnotherWCFEndPointAddress" 
  value="https:///AnotherService/MyanotherService"/>
 <add key="Author" value="Song Li"/>
 <add key="Version" value="1.0.0.0"/>
 <add key="DeploymentTime" value="01/01/2010"/>
 <add key="CopyRight" value="The Code Project Open License (CPOL)"/>
 <add key="OtherSilverlightApplicationInfo" 
  value="Whatever needed to send to Silverlight application @ deployment time"/>
</appSettings>

此 XML 块需要直接添加到 Web.config 文件中的“<configuration>”标记内。

在 Default.aspx 中托管 Silverlight 应用程序并将配置传递给 Silverlight 对象

为了在“Default.aspx”文件中托管 Silverlight 应用程序,我们按如下方式修改“Default.aspx”代码

<%@ Page Language="C#" 
    AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="SilverlightConfigurationDemoWeb.Default" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Silverlight Configuration Demonstration</title>
    
    <!-- Link the Microsoft generated style -->
    <link href="Styles/SilverlightDefault.css" 
       rel="stylesheet" type="text/css" />
    
    <!-- Link the Microsoft generated JAVA scripts -->
    <script src="JS/Silverlight.js" type="text/javascript"></script>
    <script src="JS/SilverlightDefault.js" type="text/javascript"></script>
</head>
 
<body>
    <form id="frmMain" runat="server">
    <div>
        <object data="data:application/x-silverlight-2,"
            type="application/x-silverlight-2"
            width="100%" height="100%">
    <param name="source" value="ClientBin/SilverlightConfigurationDemo.xap"/>
    <param name="onError" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="3.0.40624.0" />
    <param name="autoUpgrade" value="true" />
    
    <!-- This is ASP.NET code behind accessible object to add the configuration -->
    <asp:Literal ID="ParamInitParams" runat="server"></asp:Literal>
    
    <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" 
          style="text-decoration:none">
          
      <img src="http://go.microsoft.com/fwlink/?LinkId=108181" 
        alt="Get 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>
</html>

您会注意到“Default.aspx”文件中的代码与 Visual Studio 在“SilverlightConfigurationDemoTestPage.aspx”文件中生成的代码非常相似。由于 Microsoft 提到的 浏览器兼容性问题,我不想对 Visual Studio 生成的代码进行重大更改。我所做的唯一更改是将 Visual Studio 创建的 CSS 样式和 JavaScript 代码内联到不同的文件中。然后,我在“Default.aspx”中链接它们,以使代码干净。

需要提及的一点是 ASP.NET Literal 对象“ParamInitParams”,该对象插入到 ASP.NET 页面中表示 Silverlight 应用程序的“<object>”标记内。这是我们将配置信息传递到 Silverlight 对象的地方。配置信息将由“Default.aspx.cs”文件中的 C# 代码写入此 Literal 对象,如下所示

using System;
using System.Web;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace SilverlightConfigurationDemoWeb
{
    public partial class Default : System.Web.UI.Page
    {
        private void SaveSilverlightDeploymentSettings(Literal litSettings)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
 
            StringBuilder SB = new StringBuilder();
            SB.Append("<param name=\"InitParams\" value=\"");
 
            int SettingCount = appSettings.Count;
            for (int Idex = 0; Idex < SettingCount; Idex ++)
            {
                SB.Append(appSettings.GetKey(Idex));
                SB.Append("=");
                SB.Append(appSettings[Idex]);
                SB.Append(",");
            }
            SB.Remove(SB.Length - 1, 1);
            SB.Append("\" />");
 
            litSettings.Text = SB.ToString();
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            SaveSilverlightDeploymentSettings(ParamInitParams);
        }
    }
}

SaveSilverlightDeploymentSettings”函数从 Web.config 文件读取应用程序设置,并将信息作为逗号分隔的键值对写入 Literal 对象“ParamInitParams”。键值对的键和值用等号“=”分隔。

在 Silverlight 应用程序中访问配置信息

为了使 Silverlight 应用程序能够访问传递过来的配置信息,我们将向 App.xaml 后台代码文件的“App”类添加一个公共变量“DeploymentConfigurations”,并在“Application_Startup”函数中使用启动事件参数“e.InitParams”对其进行初始化。

public IDictionary<string, string> DeploymentConfigurations;
 
private void Application_Startup(object sender, StartupEventArgs e)
{
 DeploymentConfigurations = e.InitParams;
 this.RootVisual = new MainPage();
}

初始化后,“DeploymentConfigurations”变量引用一个“Dictionary”类型的对象。每个单独的配置参数都以键值对的形式存储在此“Dictionary”中。由于“DeploymentConfigurations”变量定义在“App”类中,因此它在整个 Silverlight 应用程序中都是可访问的。

为了演示一种从 Silverlight 应用程序访问配置参数的方法,我们将对应用程序的主 XAML 文件“MainPage.xaml”进行如下更改

<UserControl 
    xmlns:data="clr-namespace:System.Windows.Controls;
                assembly=System.Windows.Controls.Data"  
    x:Class="SilverlightConfigurationDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="Verdana">
    
    <Grid x:Name="LayoutRoot" Margin="20, 20, 20, 20">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="45"/>
        </Grid.RowDefinitions>
    
        <TextBlock Grid.Row="0"
           Text="Configure Silverlight Application 
                 from Web.config File Demonstration" 
           HorizontalAlignment="Center" 
           FontSize="14" 
           FontWeight="Bold" />
    
        <data:DataGrid Grid.Row="1"
           x:Name="dgConfigurations" AutoGenerateColumns="True"
           HeadersVisibility="All"  GridLinesVisibility="All"
           RowHeight="45" 
           RowBackground="White" 
           ColumnHeaderHeight="50"
           IsReadOnly="True" CanUserResizeColumns="True"
           VerticalAlignment="Stretch" 
           HorizontalAlignment="Stretch" />
            
        <Grid x:Name="ButtonRoot" 
                Grid.Row="2" HorizontalAlignment="Right">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="300"></ColumnDefinition>
                <ColumnDefinition Width="20"></ColumnDefinition>
                <ColumnDefinition Width="250"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            
            <Button x:Name="GetApplicationName" 
                Grid.Column="0" FontSize="12" 
                Content="Get Application Name from Configuration" 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Center"
                Click="GetApplicationName_Click"/>
            
            <Button x:Name="DisplayAllConfiguration" 
                Grid.Column="2" FontSize="12" 
                Content="Display Configuration Information" 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Center"
                Click="DisplayAllConfiguration_Click"/>
        </Grid>
    </Grid>
</UserControl>

在“MainPage.xaml”中,我们添加了一个“DataGrid”和两个“Button”控件。在一个“Button”控件的 Click 事件中,我们将所有配置数据绑定到“DataGrid”。

private void DisplayAllConfiguration_Click(object sender, RoutedEventArgs e)
{
  App application = (App)Application.Current;
  dgConfigurations.ItemsSource = application.DeploymentConfigurations;
}

在另一个“Button”控件的 Click 事件中,我们将使用我们在配置参数时在“Web.config”文件中使用的“key”来获取特定的配置项。

private void GetApplicationName_Click(object sender, RoutedEventArgs e)
{
  App application = (App)Application.Current;
  string ApplicationName = application.DeploymentConfigurations["ApplicationName"];
    
  MessageBox.Show(ApplicationName);
}

运行 Silverlight 应用程序

在 Visual Studio 中将项目“SilverlightConfigurationDemoWeb”设置为启动项目,并将“Default.aspx”文件设置为启动页后,我们可以在调试模式下运行该应用程序。下图显示了应用程序在 Google Chrome 中运行的情况。

Run Application

单击“显示配置信息”按钮,Web.config 中的所有配置信息将显示在“DataGrid”中。单击“从配置获取应用程序名称”按钮,将通过配置键从全局“Dictionary”引用“DeploymentConfigurations”中检索配置项“ApplicationName”,并使用“MessageBox”显示。

结论

本文介绍了一种使用主机 ASP.NET 应用程序的“Web.config”文件配置 Silverlight 应用程序的简单方法。基本思想是在 ASP.NET 中从“web.config”文件读取配置信息,并将其作为逗号分隔的文本字符串写入 Silverlight 对象的“InitParams”启动参数。当 Silverlight 应用程序启动时,此信息将被分配给“App”类中的一个公共变量,因此配置在整个 Silverlight 应用程序中都是全局可访问的。

关注点

  1. 在 Silverlight 2 中,Silverlight 应用程序被插入到主机 ASPX 页面中作为 ASP.NET Web 控件。直接将配置信息写入 Silverlight Web 控件比使用我们为 Silverlight 3 使用的“Literal”Web 控件要容易得多。这并非坏事,因为本文使用的技术几乎可以应用于所有网页编写方法,例如 ASP、JSP 和 Servlets。
  2. 在将配置信息写入托管的 ASPX 页面时,信息以逗号分隔的字符串形式写入,并使用“=”分隔键和参数值。因此,我们应该避免在配置信息中使用逗号或“=”号。由于几乎从不需要在 Silverlight 应用程序中配置数据库连接字符串,因此我认为这并不是一个大问题。但是,如果您确实需要在配置键或值中传递逗号或“=”,则需要转义这两个特殊字符。
  3. 配置以纯文本形式写入 ASPX 页面,任何人都可以通过查看托管网页的源代码来阅读。如果安全是您的顾虑,则应加密您的信息。
  4. 在大多数生产环境中,您可能希望在“Web.config”中同时配置 ASP.NET 主机和 Silverlight 应用程序。在这种情况下,您可能需要识别 Silverlight 应用程序的配置项,并仅将这些项传递给 Silverlight。

历史

这是本文的第一个版本。

© . All rights reserved.