C# 如何从 MVC4 中的 web.config 获取字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18483826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:21:12  来源:igfitidea点击:

How to get a String value from web.config in MVC4

c#asp.net-mvcasp.net-mvc-4azure

提问by iburak

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 值,我通过硬编码在 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.config 文件中获取值?

采纳答案by juhan_h

Use:

用:

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

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

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

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.config 文件的 appSettings 元素读取的值始终为 String 类型。如果 Web.config 文件中不存在指定的键,则不会发生错误。相反,返回一个空字符串。

回答by Srinivas

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

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

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