繁体   English   中英

Asp.net core 6 Program.cs文件中appsettings.json的使用方法

[英]How to use appsettings.json in Asp.net core 6 Program.cs file

我正在尝试在我的 Asp.net 核心 v6 应用程序 Program.cs 文件中访问 appsettings.json,但是在这个版本的 .Net 中,Startup class 和 Program class 被合并在一起,使用和另一个语句被简化并从 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";

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

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

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

appsettings.json 默认包含,可以直接使用。 如果要显式包含文件,可以像这样包含它们

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

像这样的依赖注入

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

如果我们在 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;

ETC....

假设一个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"];
});

//...

创建一个类:

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,因此这是双赢的。

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

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

应用设置.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

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

在 .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");

这就是您在 Program.cs 文件中获取 appsettings.json 值的方法。 这是样本

appsettings.json文件

  "Jwt": {
    "Key": "ThisismySecretKey",
    "Issuer": "www.joydipkanjilal.net"
  },

获取Program.cs文件中的值

var app = builder.Build();
var config = app.Configuration;
var key = config["Jwt:Key"];
var issuer = config["Jwt:Issuer"];

通过注入检索appsettings.json部分值

appsettings.json部分:

{
  "AppSettings": {
    "Key": "Value"
  }
}

AppSettings.cs

public class AppSettings
{
    public string Key { get; set; }
}

Program.cs

builder.Services.AddOptions();
builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("AppSettings"));

通过构造函数注入IOptions<>

private readonly AppSettings _appSettings;

public HomeController(
    IOptions<AppSettings> options)
{
    _appSettings = options.Value;
}

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

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

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

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

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

应用设置.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");

你可以使用这个方法

builder.Configuration.GetConnectionString("<connection string name>");

由于我的应用程序是一个 consol .NET Core 6 应用程序,我必须先安装一个 nuget 包:

  • Microsoft.Extensions.Hosting
  • Microsoft.Extensions.Configuration

然后添加它们的相关用途:

  • 使用 Microsoft.Extensions.Configuration;
  • 使用 Microsoft.Extensions.Configuration;

然后我将此代码添加到 Program.cs 文件中

// Build a config object, using env vars and JSON providers.
IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();
Settings settings = config.GetRequiredSection("Settings").Get<Settings>();

我有一个 Settings.cs class 来接受我的 appsettings.json 文件中的值

设置.cs

internal class Settings
{
    public static string Setting1 { get; set; }
    public static string Setting2 { get; set; }
    public static string Setting3 { get; set; }

}

和 AppSettings.json

"Settings": {
    "Setting1": "yep",
    "Setting2": "nope",
    "Setting3": "kjkj"
  }

来自 Microsoft 的此资源帮助我了解新的 .NET Core 6 架构

https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM