如何在Silverlight中使用Web配置文件

10

我试图在Silverlight中使用我的web.config文件。

我在web.config文件中添加了以下内容:

<configuration>
  <appSettings>
    <add key="FileHeader" value="file://***.com/Builds/"/>
    <add key="WebHeader" value="http://***.com/dev/builds"/>    
  </appSettings>

我试图像这样使用它们

string temp= System.Configuration!System.Configuration.ConfigurationManager.AppSettings.Get("FileHeader");

然而它并不起作用,会出现错误信息"只有赋值、调用、递增、递减...可以被用作语句"

3个回答

20

你无法从Silverlight应用程序中读取web.config文件,因为Silverlight应用程序在客户端(浏览器中)运行,而不是在服务器上。

从您的服务器代码中,您可以使用以下方法访问应用程序设置

string temp = Configuration.ConfigurationManager.AppSettings["FileHeader"];

但是你必须将它们发送给客户端。你可以使用InitParams来实现这一点。

<param name="initParams" value="param1=value1,param2=value2" />

在你的服务器代码(Default.aspx的Page_Load事件)中,你可以循环遍历所有的AppSettings,并动态创建initParams的值。

在Silverlight应用程序中,你可以在Application_Startup事件中访问这些参数:

private void Application_Startup(object sender, StartupEventArgs e) 
{           
   this.RootVisual = new Page();
   if (e.InitParams.ContainsKey("param1"))
      var p1 = e.InitParams["param1"];
}

或者遍历所有参数并将它们存储在配置字典中。这样,您就可以在客户端的Silverlight应用程序中拥有您的应用设置。


8

由于SL .NET Framework中不存在配置命名空间,因此您无法从Silverlight应用程序中读取web.config,但您可以执行以下操作:

public static string GetSomeSetting(string settingName)
        {
            var valueToGet = string.Empty;
            var reader = XmlReader.Create("XMLFileInYourRoot.Config");
            reader.MoveToContent();

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "add")
                {
                    if (reader.HasAttributes)
                    {
                        valueToGet = reader.GetAttribute("key");
                        if (!string.IsNullOrEmpty(valueToGet) && valueToGet == setting)
                        {
                            valueToGet = reader.GetAttribute("value");
                            return valueToGet;
                        }
                    }
                }
            }

            return valueToGet;
        }

SL无法访问服务器中的文件,是吗?XMLFileInYourRoot.Config在哪里? - Kiquenet

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接