如何在Asp.net core 6的Program.cs文件中使用appsettings.json

157

我试图在我的Asp.net core 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 而不是硬编码的 connectionstring :
options.Configuration = "localhost:6379";

该文件已经默认加载。真正的问题是如何访问“配置”? - Panagiotis Kanavos
3
在 .net 6 版本中,没有 Startup.cs 文件和 Program.cs 文件,它们被合并在了一个名为 Program.cs 的文件中。在这种新情况下,默认情况下不会创建 Configuration,并且我们无法将其注入。 - Sajed
1
这个回答是否解决了你的问题?如何在 .Net 6 控制台应用程序中读取 appsettings.json 文件? - Michael Freidgeim
15个回答

4
在.NET 6中,appSettings.json文件的格式保持不变。
{
  "Authentication": {
    "CookieAuthentication": {
      "LoginPath": "/Security/Login"
    }
  },
  "TestValue" :  "Testing data"
}

Program.cs

var builder = WebApplication.CreateBuilder(args);

var testValue = builder.Configuration.GetValue<string>("TestValue");

var cookieAuthenticationLoginPath = builder.Configuration.GetValue<string>("Authentication:CookieAuthentication:LoginPath");

即使这个方法运行良好,@dimmits所描述的方法并没有使用CreateBuilder阶段,因此它可能更高效,因为当您创建应用程序时,构建器已经就位。 - Gerardo Verrone

2
除了@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"
  }
}

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

2
您可以使用这种方法。
builder.Configuration.GetConnectionString("<connection string name>");

1

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

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

假设你的appsettings.json文件中的设置看起来像这样:

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

这应该被标记为 .NET Core 6 的正确答案,它只带有最小的 program.cs 类。非常感谢您的示例! - Gerardo Verrone
1
“builder”在当前上下文中不存在。 - Fandango68
这总是返回空值。对于如何在Dotnet6.0中使其工作,有什么想法吗? - MC9000

1
You can also do this with the following approach. Exemplified below
    **appsettings.json**
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "AppSettings": {
        "dbConnection": "Data Source=myServerName;Initial Catalog=dbName;persist security info=True;User Id=userId;Password=testPWD;MultipleActiveResultSets=True",
        "sendereMail": "test@testdomain.com",
        "MQDetails": {
          "hostName": "testHost",
          "username": "testUser",
          "passWord": "testPwd",
          "exchangeName": "testName"
        }
      }
    }
    **AppSettings.cs**
        public class AppSettings
        {
            public string? dbConnection { get; set; }
            public string? sendereMail { get; set; }
            public Dictionary<string, string>? MQDetails { get; set; }
        }
**IDemoService.cs**
public interface IDemoService
    {
        string DemoMessage(string name);
    }
**DemoService.cs**
public class DemoService:IDemoService
    {
        public string DemoMessage(string name)
        {
            return "Welcome to you " + name;
        }
    }
    **GetConfigurationsController.cs**
    namespace DotNet6.Controller
    {
        [Route("api/[controller]")]
        [ApiController]
        public class GetConfigurationsController : ControllerBase
        {
            private readonly AppSettings appSettings;
            private readonly IDemoService _demoService;
            public GetConfigurationsController(IOptions<AppSettings> options,IDemoService demoService)
            {
                appSettings = options.Value;
                _demoService = demoService;
            }
    
            [HttpGet("appsettings")]
            public AppSettings Get()
            {
    
                return appSettings;
            }
        [HttpGet("GetMessage")]
        public string GetMessage()
        {
    
            return _demoService.DemoMessage("Barbie");
        }
        }
    }

    **Program.cs**
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddRazorPages();
    builder.Services.AddControllers();
    builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
    
    builder.Services.AddConnections();
    builder.Services.AddSingleton<IDemoService, DemoService>();
    
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen(options =>
    {
        //The generated Swagger JSON file will have these properties.
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "My API POC",
            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", "MyPOC");
            c.RoutePrefix = string.Empty;
        });
        app.UseExceptionHandler("/Error");
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllers();
    });
    
    app.Run();

enter image description here enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接