2016-10-02 110 views
0

我有一个使用Google Maps API的Visual Studio 2015 ASP.NET Core 1.0项目。目前,我可以在两个地方对API密钥进行硬编码:如何使用Windows环境变量隐藏API密钥?

1)视图的脚本标记例如,

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE"></script> 

2)项目的config.json文件例如,

{ 
    "Keys": { "GoogleMapsAPIKey": "YOUR_API_KEY_HERE" } 
} 

无论哪种方式使用源代码管理时暴露密钥,为什么不使用Windows环境变量?

在Windows系统属性中,我添加了一个名为GoogleMapsAPIKey的新环境变量并粘贴在实际的键中。

现在我该如何在脚本标记或config.json中使用这个环境变量?

该问题的目的是为了在这种情况下获得有关如何使用环境变量隐藏API密钥的一般性答案。

回答

1

添加环境变量配置提供程序。从here例如:

public Startup(IHostingEnvironment hostingEnvironment) 
{ 
    var builder = new ConfigurationBuilder() 
     .SetBasePath(hostingEnvironment.ContentRootPath) 
     .AddJsonFile("config.json") 
     .AddEnvironmentVariables(); 
} 

如果你只想隐藏在开发过程中的关键,你可以使用user secrets