In ASP .NET Core Web Applications I have noticed that the connection string can be put into apsettings.jso n or secret.json file as follows:
appsettings.json
{
"ConnectionStrings": {
"DBConnectionString": "DefaultEndpointsProtocol=https;AccountName=name;AccountKey=the_key;EndpointSuffix=core.windows.net"
}
}
secret.json
{
"ConnectionStrings:DBConnectionString": "DefaultEndpointsProtocol=https;AccountName=name;AccountKey=the_key;EndpointSuffix=core.windows.net"
}
And, it is used in the startup.cs .
public class startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDBContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DBConnectionString")));
}
}
In the same way the following is a how the connection string is passed in one of the controllers in the ASP .NET Core web Application:
BlogUploadController.cs
AccountName = "MyAccount";
AccountKey = "DGKC5745dfdG_+dkfkld";
string UserConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName=name;AccountKey=DGAKSECCDI654D_FGd;EndpointSuffix=core.windows.net", AccountName, AccountKey);
You can see that I have put the "connection string", and the "AccountKey" directly in the code (which is vulnarable for security threats). Can anybody how to put in the apsettings.json or Secret.json like I have put the database connection string in the above exmple.
Thanks in advance.
Adding things to the appsettings.json
is a simple as editing the JSON. Take the custom appsettings.json
below:
{
"Setup": "Setup Value",
"Config": {
"Key": "My Key",
"Token": "My Token"
}
}
In order to get the custom values from the above, you can use the Configuration variable in the setup.cs
file in APS.NET Core.
string setup = Configuration["Setup"];
To get a value such as Config.Key
, you separate the names with a colon :
, such as this:
string key = Configuration["Setup:Key"];
string token = Configuration["Setup:Token"];
Do be aware that using appsettings.json
to hold secrets is a bad idea, as appsettings.json
is usually a public document and not a secrets file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.