我正在从事.NET 5 Web API项目。我需要使用外部API(Rapidapi.com等)。这些网站给了我一个API令牌。
我知道应该隐藏它,所以Github没有人会看到它。
但我也应该将我的API密钥发送给我的老师,以便他们也可以访问,或者可以使用自己的API键访问。
-
我应该在哪里存储它?
-
我应该如何存储它?
-
我该怎么称呼?
我知道如何在JavaScript中执行此操作(非常简单,创建.env文件,并将其称为EinvironMet.Apikey),但是我不知道该如何在.NET中执行此操作。
我需要一个简单的解决方案,例如在JavaScript中。
我找到了一个解决方案。您可以将部分添加到 appSettings.json
之类的中:
"API_KEY": "blablabla"
然后在控制器中使用此部分:
private readonly IConfiguration _configuration;
为此创建一个构造函数
public CurrencyCalculatorAPI(IConfiguration configuration)
{
_configuration = configuration;
}
,然后使用这样的API键,
var apiKey = _configuration.GetValue<string>("API_KEY");
可以随时随地使用它。
I am working on an .NET 5 web API project. I needed to use an external API (rapidapi.com etc.). These websites gave me an API token.
I know should hide it, so no one at GitHub would see it.
But also I should send my API key to my teacher so they get access too, or they can access with their own API key.
-
Where should I store it?
-
How should I store it?
-
How can I call it?
I know how to do it in JavaScript, (it's so easy, create .env file, and call it einvironmet.apikey), but I don't know how to do this in .NET.
I need a simple solution like in JavaScript.
I found a solution. You can add a section to the appsettings.json
like this:
"API_KEY": "blablabla"
Then use this in your controller:
private readonly IConfiguration _configuration;
Create a constructor for this
public CurrencyCalculatorAPI(IConfiguration configuration)
{
_configuration = configuration;
}
Then use your API key like this
var apiKey = _configuration.GetValue<string>("API_KEY");
You can use it wherever you want.
发布评论
评论(1)
您应该使用“用户秘密”,例如。
在Visual Studio中非常容易,您可以右键单击您的项目并选择“管理用户秘密”。这将在此位置创建一个文件:
%appData%\ Microsoft \ usersecrets \&lt; user_secrets_id&gt; \ secrets.json
此文件在您的项目外部,因此它永远不会成为您在github。
You should use "User secrets", as described by Microsoft.
It's very easy in Visual Studio where you just right click your project and choose "Manage User Secrets". This will create a file in this location:
%APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json
This file is outside your project so it will never be a part of what you have in Github.