Popular blog tags

All kind of ASP.NET Core 6.x Configuration

Published

ASP.NET Core Configuration can come from various sources as follows:

ASP.NET Core Configuration can obtain some values from various sources.  we can use and combine various sources for configuration settings (values): Files (JSON, XML, INI) Command-line arguments Environment variables In-memory .NET objects Azure Key Vault     

One of default sources is appsettings.json file that comes with ASP.NET Core  templates.It is  key-value pairs collection.    

You can also create custom providers and plug them into the ASP.NET Core system.  

 

.Net 6.x

builder.Configuration["Site:Domain"]

In Program.cs, the WebApplicationBuilder is created shown below.

var builder = WebApplication.CreateBuilder(args);

//Add  Configure Options https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/configuration/index/samples/6.x/ConfigSample/Program.cs
builder.Configuration.AddJsonFile("appsettings.json");

#region 配置cookie认证方式
//see:https://stackoverflow.com/questions/69722872/asp-net-core-6-how-to-access-configuration-during-startup
// If you don't want the cookie to be automatically authenticated and assigned to HttpContext.User, 
// remove the CookieAuthenticationDefaults.AuthenticationScheme parameter passed to AddAuthentication.

var sitedomain = builder.Configuration["Site:Domain"];


builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Customer/LogIn";
        options.LogoutPath = "/Customer/LogOut";
#if !DEBUG
             options.Cookie.Domain = sitedomain;//设置Cookie的域为根域,这样所有子域都可以发现这个Cookie
#endif
                }
   );



#endregion


var app = builder.Build();

ConfigurationManager

WebApplicationBuilder returned by WebApplication.CreateBuilder(args) exposes Configuration and Environment properties:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration;
IWebHostEnvironment environment = builder.Environment;

WebApplication returned by WebApplicationBuilder.Build() also exposes Configuration and Environment:

var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;

 

builder.Configuration

come from:https://github.com/nopSolutions/nopCommerce/blob/1cfa5b88ddd732f5919c76e2be914e6881612efb/src/Presentation/Nop.Web.Framework/Infrastructure/Extensions/ServiceCollectionExtensions.cs#L52

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDI();

var configuration = builder.Configuration;

//注册所有服务
builder.Services.AddCustomRegistrarServices(configuration);