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"];
}