简体   繁体   English

web.config c#.net web应用程序

[英]web.config c# .net web application

How to read a personal section in a web.config ? 如何阅读web.config中的个人部分?

<MyPersonalSection>
    <add name="toto" enable="true" URL="http://localhost:43242" />
    <add name="titi" enable="false" URL="http://localhost:98762" />
<MyPersonalSection/>

I'd like to get the enable value and/or URL value with the name value. 我想获取名称值的启用值和/或URL值。

I also have this mistake : Unrecognized configuration section MyPersonalSection 我也有这个错误:无法识别的配置部分MyPersonalSection

I been trying 我一直在努力

var config = ConfigurationManager.GetSection("MyPersonalSection"); var config = ConfigurationManager.GetSection(“MyPersonalSection”);

是一个很酷的例子。

You don't need to write a custom configuration handler to get what you want. 您无需编写自定义配置处理程序即可获得所需内容。 There are built-in configuration handlers that you can use if you simply want key-value entries. 如果您只是想要键值输入,可以使用内置的配置处理程序。 But, you'll have to use key instead of name and value instead of URL . 但是,您必须使用key而不是namevalue而不是URL For example: 例如:

<configuration>
 <configSections>
  <section name="MyPersonalSection" type="System.Configuration.NameValueSectionHandler" />
 </configSections>
<MyPersonalSection>
    <add key="toto" value="http://localhost:43242" />
    <add key="titi" value="http://localhost:98762" />
</MyPersonalSection>
</configuration>

And you can access them via code: 您可以通过代码访问它们:

var myValues = ConfigurationSettings.GetConfig("MyPersonalSection") as NameValueCollection;
var url = myValues["toto"];

I would suggest naming your keys in a way that makes it clear what the value should be, like "totoUrl" and "titiUrl". 我建议以一种明确值应该是什么的方式命名你的密钥,比如“totoUrl”和“titiUrl”。

If you want something other than string value pairs, you'll have to write your own custom handler. 如果您想要除字符串值对之外的其他内容,则必须编写自己的自定义处理程序。

You can add appSettings section in your web.config with key that you will need. 您可以使用您需要的密钥在web.config中添加appSettings部分。 For example: 例如:

<configuration>
   <appSettings>
      <add key="FirstUrl" value="http://localhost:43242"/>
      <add key="SecondUrl" value="http://localhost:98762" />
    </appSettings>
 ...
</configuration>

So, since aspx.cs file, you can declare directive 所以,从aspx.cs文件开始,你可以声明指令

using System.Configuration;

And later, you can retrieve FirstUrl value in this way: 之后,您可以通过以下方式检索FirstUrl值:

 var myUrl = ConfigurationManager.AppSettings["FirstUrl"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM