从Web.Config读取变量

Ami*_*ail 89 .net c# asp.net web-config

如何添加和读取web.config文件中的值?

Pra*_*uja 136

给出以下web.config:

<appSettings>
     <add key="ClientId" value="127605460617602"/>
     <add key="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)

用法示例:

using System.Configuration;

string clientId = ConfigurationManager.AppSettings["ClientId"];
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];
Run Code Online (Sandbox Code Playgroud)

  • +1很好的答案.但是有一点需要注意 - 你不需要显式地调用`ToString`,因为`AppSettings`上的索引器会返回`string`类型的值 (15认同)

Muh*_*tar 70

我建议你不要修改web.config,因为每次更改时,它都会重启你的应用程序.

但是,您可以使用读取web.config System.Configuration.ConfigurationManager.AppSettings

  • 您可以将此类变量存储在加密的 XML 文件中。 (2认同)
  • 是的,XML 文件是更好的主意。或者您可以将其存储在数据库中并添加到application_start(Global.asax)中,将其放入应用程序变量中并在应用程序中使用它们。这些变量仅在应用程序中分配一次,如果您的应用程序重新启动,这些变量将再次分配。 (2认同)

Llo*_*ell 17

如果您需要基础知识,可以通过以下方式访问密钥:

string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();
Run Code Online (Sandbox Code Playgroud)

要访问我的Web配置键,我总是在我的应用程序中创建一个静态类.这意味着我可以在任何需要的地方访问它们,而且我没有在我的应用程序中使用字符串(如果它在Web配置中发生变化,我必须经历所有更改它们的事件).这是一个示例:

using System.Configuration;

public static class AppSettingsGet
{    
    public static string myKey
    {
        get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
    }

    public static string imageFolder
    {
        get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
    }

    // I also get my connection string from here
    public static string ConnectionString
    {
       get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
    }
}
Run Code Online (Sandbox Code Playgroud)


RPM*_*984 6

假设密钥包含在内部 <appSettings>节点内:

ConfigurationSettings.AppSettings["theKey"];
Run Code Online (Sandbox Code Playgroud)

至于"写作" - 简单地说,不要.

web.config不是为此设计的,如果您要不断更改值,请将其放在静态帮助程序类中.