Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从app.config读取密钥_C#_Asp.net_Asp.net Web Api - Fatal编程技术网

C# 从app.config读取密钥

C# 从app.config读取密钥,c#,asp.net,asp.net-web-api,C#,Asp.net,Asp.net Web Api,从app.config读取密钥不起作用 我的解决方案中有4个层: 业务层 数据访问层 表示层 共享层 我在共享层中添加了这个app.config文件: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="TEST" value="ItsWorking" /> </appSettings> </config

app.config
读取密钥不起作用

我的解决方案中有4个层:

  • 业务层
  • 数据访问层
  • 表示层
  • 共享层
我在共享层中添加了这个
app.config
文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="TEST" value="ItsWorking" />
  </appSettings>
</configuration>

但是它返回null

配置仅从正在执行的项目程序集读取,因此您只需要在可执行项目中进行访问,并且可以从所有其他项目中进行访问

也许您可以使用带有接口的configurationProvider,通过IOC,您可以从所有项目进行访问

您可以在所有项目中使用此接口,并且只有在正确实现配置的情况下,才可以实现app.config、xml、.text、DB或任何源的接口

  public class Configurations : IConfigurations
    {
      public string TEST => ConfigurationManager.AppSettings["TEST"]; 
    }

您可以检查此问题:
ConfigurationManager.AppSettings
将读取当前执行程序集的
.config
文件。如果代码在web应用程序(例如ASP.NET MVC或web API)中运行,则应将
appSettings
标记添加到根
web.config
@FedericoDipuma谢谢,它起作用了。@FedericoDipuma将您的注释移动到答案,以便我可以将其标记为正确答案。
public interface IConfigurations
{
  string TEST {get;}
}
  public class Configurations : IConfigurations
    {
      public string TEST => ConfigurationManager.AppSettings["TEST"]; 
    }