簡體   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