2017-04-09 58 views
1

我有一个MVC项目,并试图将我的API密钥存储在单独的配置文件中,在将代码推送到Git时我将忽略它。根据MSDN,我应该能够将它们存储在一个app.config喜欢像这样C#无法从MVC中的App.config文件读取

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

那么我应该可以从文件中读取通过在模型建立方法

public class KeyTest 
    { 
    public string KeyTestCall() 
    { 
     string testkey = ConfigurationManager.AppSettings.Get("APIKey"); 
     return testkey; 
    } 
    } 

和然后调用我的控制器中的方法来从我的App.config文件中分配值(只是让我知道我正在获取值)。

public void Testing() 
    { 
     KeyTest k = new KeyTest(); 
     ViewBag.x = k;  
    } 

在任何时候代码都不会破坏断点,构建会成功,我不知道我是否得到值。任何帮助深表感谢。谢谢!

回答

0

除了上述(重:web.config VS app.config),如果你想从源代码控制删除“秘密”,this is one way to do it

web.config

<?xml version="1.0" encoding="utf-8"?> 
    <cofiguration> 
     .... 
     <appSettings file="AppKeys.config"> 
      <add key="SomeOtherSettingThatHasNoSecrets" value="foo" /> 
      ... 

然后在separte AppKeys.config文件(你能说出这个whatever.co nfig,如上面提到的样品),你不增加Git /源控制:

<appSettings> 
    <add key="SomeSecretKey" value="the secret" /> 
    ... 

注意AppKeys.config有一个XML声明。

Hth。

2

对于作为MVC应用程序的Web应用程序,例如,它是一个Web.config文件,而不是一个App.config

+0

即使在将appSettings移入Web.config – Mike

+0

之后,我也有同样的问题使用访问器。 'ConfigurationManager.AppSettings [ “APIKey”]' – Haney