【问题标题】:How to use appsettings.json in Asp.net core 6 Program.cs file如何在 Asp.net core 6 Program.cs 文件中使用 appsettings.json
【发布时间】:2021-11-22 04:54:15
【问题描述】:

我正在尝试访问我的 Asp.net 核心 v6 应用程序 Program.cs 文件中的 appsettings.json,但在这个版本的 .Net 中,Startup 类和 Program 类合并在一起,并且简化了 using 和另一个语句,并且从 Program.cs 中删除。在这种情况下,如何访问 IConfiguration 或如何使用依赖注入?

已编辑: 这是 Asp.net 6 为我创建的默认 Program.cs

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

例如,我想在这一行中使用 appsettings.json 而不是硬类型的连接字符串:

options.Configuration = "localhost:6379";

【问题讨论】:

  • 默认情况下该文件已加载。真正的问题是如何访问Configuration
  • .net 版本 6 中没有 Startup.cs 和 Program.cs 和 Startup.cs 在 Program.cs 文件中合并在一起,在这种新情况下,默认情况下没有创建配置,我们无法注入它@PanagiotisKanavos

标签: c# asp.net-core .net-core .net-6.0


【解决方案1】:

虽然上面的示例有效,但执行此操作的方法如下:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration["Redis"];
});

WebApplicationBuilder 有一个配置对象作为您可以使用的属性。

【讨论】:

  • 假设我在 dev json 文件中创建了名为 key1 的密钥,并在 prod json 文件中创建了名为 key2 的密钥,然后当我在 Visual Studio 中运行项目时,它正在读取两个密钥.它不应该只从 dev json 文件中读取密钥吗?
【解决方案2】:

默认包含appsettings.json,可以直接使用。 如果你想明确地包含文件,你可以像这样包含它们

builder.Configuration.AddJsonFile("errorcodes.json", false, true);

还有像这样的依赖注入

builder.Services.AddDbContext<>() // like you would in older .net core projects.

【讨论】:

  • 这在 .NET 6 中不起作用。AddDbContext 不存在。是否缺少使用?
  • 我同意这在 NET 6 中不起作用。AddJsonFile 方法不是 ConfigurationBuilder 类的一部分。
  • @OliverNilsen 绝对是。您可以通过 'var config = new ConfigurationBuilder().AddJsonFile("x.json").Build();' 进行测试并且您可以对 Mayur Ekbote 提到的 builder.Configuration.AddJsonFile(...) 执行相同操作
  • 它有效,但我需要先在 .NET Core 6 中手动添加 NuGet 数据包。
【解决方案3】:

假设一个 appsettings.json

{
    "RedisCacheOptions" : {
        "Configuration": "localhost:6379"
    }
}

没有什么能阻止您构建配置对象以提取所需的设置。

IConfiguration configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = configuration["RedisCacheOptions:Configuration"];
});

//...

【讨论】:

  • 是的,这是构建它的好方法,在旧版本中,我们注入配置而不是在 Startup.cs 中构建它
【解决方案4】:

创建一个类:

public class RedisCacheOptions
{
    public string Configuration { get; set; }
}

然后,在您的 program.cs 中,执行以下操作:

var redisCacheOptions = new RedisCacheOptions();
builder.Configuration.GetSection(nameof(RedisCacheOptions)).Bind(redisCacheOptions);

您现在可以通过简单的说来访问配置信息:

redisCacheOptions.Configuration

现在假设您在 appSettings.json 中有一个 嵌套 结构,如下所示:

"AuthenticationConfiguration": {
  "JwtBearerConfiguration": {
    "Authority": "https://securetoken.google.com/somevalue",
    "TokenValidationConfiguration": {
      "Issuer": "https://securetoken.google.com/somevalue",
      "Audience": "somevalue"
    }
  }
}

那么,你的类结构会是这样的:

public class AuthenticationConfiguration
{
    public JwtBearerConfiguration JwtBearerConfiguration { get; set; } = new JwtBearerConfiguration();
}

public class JwtBearerConfiguration
{
    public string Authority { get; set; }

    public TokenValidationConfiguration TokenValidationConfiguration { get; set; } =
        new TokenValidationConfiguration();
}

public class TokenValidationConfiguration
{
    public string Issuer { get; set; }
    public string Audience { get; set; }
}

如果你这样做的话:

var authConf = new AuthenticationConfiguration();
builder.Configuration.GetSection(nameof(AuthenticationConfiguration)).Bind(authConf);

然后在您的程序中,您可以通过以下方式访问值:

AuthenticationConfiguration.JwtBearerConfiguration.Authority

这种方法可以让您不再使用魔术字符串,而且还可以获得 IntelliSense,所以这是双赢的。

【讨论】:

  • 感谢您展示builder.Configuration.GetSection()。这就是我要找的!
【解决方案5】:

如果我们在 appsettings 中有

"settings": {
    "url": "myurl",
    "username": "guest",
    "password": "guest"
  }

我们有课

public class Settings
    {
        public string Url { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }

我们也可以使用

var settings = builder.Configuration.GetSection("Settings").Get<Settings>();

var url = settings.Url; 等等......

【讨论】:

  • 这应该被标记为 .NET Core 6 的正确 Answare,它只带有最少的 startup.cs 类。非常感谢你的例子!!
【解决方案6】:

在 Program.cs 中,试试这个代码:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

ConfigurationManager configuration = builder.Configuration;

var rabbitMQSection = Configuration.GetSection("RabbitMQ");
var rabbitMQConnectionUrl = rabbitMQSection["ConnectionUrl"];

appsettings.json 文件在哪里:

"AllowedHosts": "*",
"RabbitMQ": {
    "ConnectionUrl": "amqp://guest:guest@localhost:5672/"
}

【讨论】:

    【解决方案7】:

    在 .NET 6 中

    appSettings.json

    {
      "Authentication": {
        "CookieAuthentication": {
          "LoginPath": "/Security/Login"
        }
      },
      "TestValue" :  "Testing data"
    }
    

    程序.cs

    var builder = WebApplication.CreateBuilder(args);
    
    var testValue = builder.Configuration.GetValue<string>("TestValue");
    
    var cookieAuthenticationLoginPath = builder.Configuration.GetValue<string>("Authentication:CookieAuthentication:LoginPath");
    

    【讨论】:

    • 即使这样工作正常,下面描述的@dimmits 的方法也不会使用 CreateBuilder 阶段,并且它可能会更高效,因为在您创建应用程序时构建器已经就位。
    【解决方案8】:

    已解决:在dotnet6的program.css中获取appsetting值

    appsettings.json

      "AllowedHosts": "*",
      "ServiceUrls": {
      "EmployeeAPI": "https://localhost:44377/" },
    

    程序.cs

    var builder = WebApplication.CreateBuilder(args);    
    var provider = builder.Services.BuildServiceProvider();
    var configuration = provider.GetService<IConfiguration>();
    SD.EmployeeAPIBase = configuration.GetValue<string>("ServiceUrls:EmployeeAPI");
    

    类静态变量:

    public static class SD //Static Details
    {
        public static string EmployeeAPIBase { get; set; }     
    }
    

    最后,使用完整的网址

    URL = SD.EmployeeAPIBase + "api/EmpContact/GetGovernates"
    

    【讨论】:

      【解决方案9】:

      您可以像这样在Program.cs 中从appsettings.json 文件中读取设置值:

      var dbConnectionString = builder.Configuration.GetSection("ConnectionStrings:TestDbConnection").Value;
      

      考虑到您的appsettings.json 文件中的设置如下所示:

        "ConnectionStrings": {
          "TestDbConnection": ""
        }
      

      【讨论】:

      • 这应该被标记为仅带有最小 program.cs 类的 .NET Core 6 的正确答案。非常感谢您的示例!
      【解决方案10】:

      除了@dimmits 和@Sarwarul Rizvi 回答之外,如果你想读取一个普通的键值对而不是映射到一个复杂的对象,你可以使用:

      appsettings.json

      {
        "Logging": {
          "LogLevel": {
            "Default": "Information",
            "Microsoft": "Information",
            "Microsoft.AspNetCore.SpaProxy": "Information",
            "Microsoft.Hosting.Lifetime": "Information"
          }
        },
        "AllowedOrigins": "https://localhost:444/YourApplicationUri;https://localhost:7211",
        "ConnectionStrings": {
          "Default": "Connection String details"
        }
      }
      
      

      程序.cs

      ConfigurationManager configuration = builder.Configuration;
      var allowedOrigins = configuration.GetValue<string>("AllowedOrigins");
      

      这可以用于例如配置 Cors

      if (!String.IsNullOrEmpty(allowedOrigins))
      {
          builder.Services.AddCors(options =>
          {
              var origins = allowedOrigins.Split(";");
      
              options.AddPolicy("CorsPolicy", policy =>
              {
                  policy.AllowAnyMethod()
                      .AllowAnyHeader()
                      .AllowCredentials()
                      .WithOrigins(origins);
              });
          });
      }
      

      以后及以下 app.UseRouting();

      app.UseCors("CorsPolicy");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-21
        • 2022-06-13
        • 2019-11-19
        • 1970-01-01
        • 2022-12-29
        • 2022-08-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多