如何从MVC4中的web.config获取String值

ibu*_*rak 16 c# asp.net-mvc azure asp.net-mvc-4

我想获得一个logFilePath值,我将硬编码提供给appSettings.我试图达到关键价值

System.Configuration.Configuration rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
System.Configuration.KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings["azureLogUrl"];
string pathValue =  customSetting.Value;
Run Code Online (Sandbox Code Playgroud)

但我得到null引用异常.如何从web.config文件中获取值?

juh*_*n_h 50

使用:

string pathValue = ConfigurationManager.AppSettings["azureLogUrl"];
Run Code Online (Sandbox Code Playgroud)

您不需要将其强制转换为字符串并检查空值,因为文档说明:

从Web.config文件的appSettings元素读取的值始终为String类型.如果Web.config文件中不存在指定的密钥,则不会发生错误.而是返回一个空字符串.

  • 需要使用 System.Configuration 添加; (3认同)

Sri*_*vas 5

您可以像这样从 web.config 获取值:

string pathValue = WebConfigurationManager.AppSettings["azureLogUrl"].ToString();
Run Code Online (Sandbox Code Playgroud)