如何从web获取字符串值。配置在MVC4

时间:2022-01-06 20:53:40

I want to get a logFilePath value which I gave by hardcode in to appSettings. I am trying to reach the key value by

我想获取一个logFilePath值,它是我通过hardcode提供给appSettings的。我正试图达到关键价值

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

but I am getting null reference exception . How can I get the value from web.config file?

但是我得到了空引用异常。如何从web中获取价值。配置文件?

2 个解决方案

#1


44  

Use:

使用:

string pathValue = ConfigurationManager.AppSettings["azureLogUrl"];

You do not need to cast this to string and check for nulls because documentation states:

您不需要将其转换为string并检查是否为nulls,因为文档说明如下:

Values read from the appSettings element of the Web.config file are always of type String. If the specified key does not exist in the Web.config file, no error occurs. Instead, an empty string is returned.

值从Web的appSettings元素中读取。配置文件总是类型为String。如果在Web中不存在指定的密钥。配置文件,没有错误发生。相反,返回一个空字符串。

#2


2  

You can get the value from web.config like this :

你可以从web上获得价值。配置是这样的:

string pathValue = WebConfigurationManager.AppSettings["azureLogUrl"].ToString();

#1


44  

Use:

使用:

string pathValue = ConfigurationManager.AppSettings["azureLogUrl"];

You do not need to cast this to string and check for nulls because documentation states:

您不需要将其转换为string并检查是否为nulls,因为文档说明如下:

Values read from the appSettings element of the Web.config file are always of type String. If the specified key does not exist in the Web.config file, no error occurs. Instead, an empty string is returned.

值从Web的appSettings元素中读取。配置文件总是类型为String。如果在Web中不存在指定的密钥。配置文件,没有错误发生。相反,返回一个空字符串。

#2


2  

You can get the value from web.config like this :

你可以从web上获得价值。配置是这样的:

string pathValue = WebConfigurationManager.AppSettings["azureLogUrl"].ToString();