C#无法从MVC

时间:2017-04-09 21:51:49

标签: c# asp.net .net git model-view-controller

我有一个MVC项目,我试图将我的API密钥存储在一个单独的配置文件中,在将代码推送到Git时我会忽略它。根据MSDN,我应该能够将它们存储在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;      
    }

代码在任何时候都不会破坏断点,构建将成功,我无法判断我是否获得了值。任何帮助深表感谢。谢谢!

2 个答案:

答案 0 :(得分:2)

对于MVC应用等网络应用,它是Web.config文件,而不是App.config

答案 1 :(得分:0)

In addition to above (re: web.config vs app.config) if you want to remove "secrets" from source control, this is one way to do it:

In web.config

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

Then in a separte AppKeys.config file (you can name this whatever.config, sample as named in the above), that you don't add to Git/source control:

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

Note that AppKeys.config doesn't have an XML declaration.

Hth.