【问题标题】:How to add a "key" and its "name" to apsettings.js in ASP .NET Core Web application如何在 ASP .NET Core Web 应用程序中向 apsettings.js 添加“密钥”及其“名称”
【发布时间】:2021-08-11 15:58:23
【问题描述】:

在 ASP .NET Core Web 应用程序中,我注意到 连接字符串 可以放入 apsettings.json 或 secret.json文件如下:

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"
}

而且,它在 startup.cs 中使用。

public class startup
{
  public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDBContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DBConnectionString")));
        }
}

问题:

以下是在 ASP .NET Core Web 应用程序中的一个控制器中传递 连接字符串 的方式:

BlogUploadController.cs

 AccountName = "MyAccount";
 AccountKey = "DGKC5745dfdG_+dkfkld";

 string UserConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName=name;AccountKey=DGAKSECCDI654D_FGd;EndpointSuffix=core.windows.net", AccountName, AccountKey);

您可以看到我已经将“连接字符串”和“AccountKey”直接放在代码中(这很容易受到安全威胁)。任何人都可以像我在上面的例子中放入数据库连接字符串一样放入 apsettings.json 或 Secret.json。

提前致谢。

【问题讨论】:

  • 谢谢您的回复先生。但我找不到办法。请你帮助我好吗。很抱歉打扰你。如果您至少可以分享一个链接,我将不胜感激。
  • 另外,请阅读this
  • 感谢@RodrigoRodrigues 的支持。我会阅读你分享的文章。

标签: c# asp.net-core asp.net-core-mvc app-secret


【解决方案1】:

appsettings.json 添加东西就像编辑 JSON 一样简单。取下面的自定义appsettings.json

{
    "Setup": "Setup Value",    
    "Config": {
        "Key": "My Key",
        "Token": "My Token"
    }
}

为了从上面获取自定义值,您可以使用 APS.NET Core 中 setup.cs 文件中的 Configuration 变量。

string setup = Configuration["Setup"];

要获取诸如Config.Key 之类的值,请用冒号: 分隔名称,例如:

string key = Configuration["Setup:Key"];
string token = Configuration["Setup:Token"];

请注意,使用appsettings.json 保存机密是一个坏主意,因为appsettings.json 通常是公开文档而不是机密文件。

【讨论】:

  • 感谢您的回答,但我有点担心。我只需要将我的一个连接字符串 (DefaultEndpointsProtocol=https;AccountName=name;AccountKey=DGAKSECCDI654D_FGd;EndpointSuffix=core.windows.net) 放入 apsettings.json。但我可以看到您的答案中有 02 作为设置和配置。因此,对于 key 我可以放置“UserConnectionString” & 对于 token 我可以放置上面的连接字符串。但是对于设置,我应该放什么?
  • appsettings 文件是完全可定制的。 json 中的第一个值是键,而第二个是值。不要使用我使用的确切代码,修改它以满足您的需要。你想要一对像cookie: "yum" 然后做一个。这完全取决于您如何配置文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 2018-12-20
  • 1970-01-01
相关资源
最近更新 更多