2017-04-09 57 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