1、扩展包 Microsoft.Extensions.Hosting
2、包括Host、WebApplication
3、示例
1)honst 注意: <Project Sdk="Microsoft.NET.Sdk">
var builder = Host.CreateDefaultBuilder(args); var app = builder.Build(); app.Run();
2)webApplictaion 注意:<Project Sdk="Microsoft.NET.Sdk.Web">
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://localhost:8888/"); builder.Services.AddControllersWithViews(); var app = builder.Build(); app.UseRouting(); app.MapGet("/", content => content.Response.WriteAsync("hello first!")); app.Run();
4、环境变量
dev(开发环境) 、SIT(集成环境)、UAT(用户测试)、PRD(生产环境)
var builder = WebApplication.CreateBuilder(args); builder.Configuration.AddJsonFile("test.Json"); builder.WebHost.UseUrls("http://localhost:8888/"); var app = builder.Build(); app.UseRouting(); app.MapGet("/", content => content.Response.WriteAsync(builder.Environment.EnvironmentName));//获取环境变量 app.MapGet("/Test", content => content.Response.WriteAsync(builder.Configuration["myValue"].ToString()));//web应用获取配置Json的值
app.MapGet("/Test1", content => content.Response.WriteAsync(app.Configuration.GetRequiredSection("myValue").Value));
app.Run();
var builder = Host.CreateDefaultBuilder(args); builder.ConfigureHostConfiguration(option => option.AddEnvironmentVariables("myValue").AddJsonFile("test.Json") );//从配置配置环境变量 var app = builder.Build(); var config = app.Services.GetRequiredService<IConfiguration>(); var logger=app.Services.GetRequiredService<ILogger<Program>>(); logger.LogInformation(config.GetValue<string>("myValue"));//从配置文件获取环境变量值 app.Run();