ApplicationBuilder
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
検索
|
最終更新
|
ヘルプ
|
ログイン
]
開始行:
[[ASP.NET Core Web]]
&color(red){※This article is based on .NET 7};
#contents
* 概要 [#w9a1afa4]
标准提供 WebApplication 和 WebApplicationBuilder 两个类,...
- WebApplicaiton代表的是运行的应用
- ApplicationBuilder 意味着由它构建的就是一个Application...
那么在ASP.NET Core框架的语义下应用(Application)可以这样...
那么HttpHandler就等于Application,由于HttpHandler通过Requ...
由于表示HttpHandler的RequestDelegate是由注册的中间件来构...
#codeprettify{{
public interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, Request...
RequestDelegate Build();
}
}}
如下所示的是针对该接口的具体实现。我们利用一个列表来保存...
#codeprettify{{
public class ApplicationBuilder : IApplicationBuilder
{
private readonly List<Func<RequestDelegate, RequestDe...
public RequestDelegate Build()
{
_middlewares.Reverse();
return httpContext =>
{
RequestDelegate next = _ => { _.Response.Stat...
foreach (var middleware in _middlewares)
{
next = middleware(next);
}
return next(httpContext);
};
}
public IApplicationBuilder Use(Func<RequestDelegate, ...
{
_middlewares.Add(middleware);
return this;
}
}
}}
在调用第一个中间件(最后注册)的时候,我们创建了一个Reque...
** 标准默认做法 [#xa976650]
Startup.cs
#codeprettify{{
namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use th...
public void ConfigureServices(IServiceCollection ...
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Titl...
});
}
// This method gets called by the runtime. Use th...
public void Configure(IApplicationBuilder app, IW...
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("...
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
}}
* 极简代码 [#cafd5c2a]
通过代码来配置
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Configure the cert and the key
builder.Configuration["Kestrel:Certificates:Default:Path"...
builder.Configuration["Kestrel:Certificates:Default:KeyPa...
var app = builder.Build();
app.Urls.Add("https://localhost:3000");
app.MapGet("/", () => "Hello World");
app.Run();
}}
* 配置 [#j3f28966]
** 改变应用content root, app name以及环境变量 [#pc9169a8]
#codeprettify{{
var builder = WebApplication.CreateBuilder(new WebApplica...
{
ApplicationName = typeof(Program).Assembly.FullName,
ContentRootPath = Directory.GetCurrentDirectory(),
EnvironmentName = Environments.Staging
});
Console.WriteLine($"Application Name: {builder.Environmen...
Console.WriteLine($"Environment Name: {builder.Environmen...
Console.WriteLine($"ContentRoot Path: {builder.Environmen...
var app = builder.Build();
}}
运行后:
#codeprettify{{
:\MyProjects\DotNetLearning\.Net6\WebApplicationDemo>dotn...
正在生成...
Application Name: WebApplicationDemo, Version=1.0.0.0, Cu...
Environment Name: Staging
ContentRoot Path: D:\MyProjects\DotNetLearning\.Net6\WebA...
}}
除了代码改变之外,还可以通过如下的环境变量来改变:
- ASPNETCORE_ENVIRONMENT
- ASPNETCORE_CONTENTROOT
- ASPNETCORE_APPLICATIONNAME
或者通过命令行参数来改变:
- --applicationName
- --environment
- --contentRoot
** 配置项 [#rf6a9fc1]
*** 添加配置source [#mab44dac]
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddIniFile("appsettings.ini");
var app = builder.Build();
}}
读取配置
默认按照如下的顺序读取配置:
+ appSettings.json
+ appSettings.{environment}.json
+ environment variables
+ 命令行参数
*** 读取配置 [#v24d3b22]
读取配置的实例:
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Reads the ConnectionStrings section of configuration a...
var connectionString = builder.Configuration.GetConnectio...
Console.WriteLine($"My connection string is {connectionSt...
var app = builder.Build();
}}
appsettings.json的内容
#codeprettify{{
{
"cnblogs": "My CNBlogs Address:https://www.cnb.com",
"AppSettings": {
"HttpUrl": "http://www.gt.com",
"Copyright": "gzbit"
},
"Person": [
{
"name": "xfmtl",
"company": "gzbit",
"address": [
{
"province": "Guizhou Province",
"city": "Guiyang City"
},
{
"province": "Yunnan Province",
"city": "Wuhua District"
}
]
},
{
"name": "C# Study",
"adress": "Microsoft"
}
],
"Book": {
"name": "C# Program",
"publish": "2020-08"
}
}
}}
Controller里读取配置的实例:
#codeprettify{{
public IActionResult Index()
{
//加载配置文件
ConfigurationBuilder configurationBuilder = new Confi...
//添加配置文件路径
configurationBuilder.SetBasePath(Directory.GetCurrent...
.AddJsonFile("appsettings.json");
var configuration = configurationBuilder.Build();
//获取博客园地址
var cnblogs = configuration["cnblogs"];
//获取Book名称
var bookname = configuration.GetValue<string>("Book:n...
//获取幸福摩天轮的第一地区名称
var addressName = configuration.GetValue<string>("Per...
//获取C# 学习的名称
var cname = configuration.GetValue<string>("Person:1:...
//获取所在公司
var companyName= configuration["AppSettings:Copyright...
return Content(cnblogs);
}
}}
*** 读取环境变量 [#rc3d0ba1]
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
Console.WriteLine($"Running in development");
}
var app = builder.Build();
}}
*** 添加日志配置 [#fb363e5f]
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Configure JSON logging to the console
builder.Logging.AddJsonConsole();
var app = builder.Build();
}}
*** 添加Service [#ub8efc2d]
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Add the memory cache services
builder.Services.AddMemoryCache();
// Add a custom scoped service
builder.Services.AddScoped<ITodoRepository, TodoRepositor...
var app = builder.Build();
}}
*** 改变webroot [#r8da6aca]
默认情况下webroot是在相对路径下的wwwroot下,如果要改变这...
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Look for static files in webroot
builder.WebHost.UseWebRoot("webroot");
var app = builder.Build();
}}
*** 定制DI容器 [#de11d13e]
我们这里使用Autofac
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacService...
// Register your own things directly with Autofac here. D...
// call builder.Populate(), that happens in AutofacServic...
// for you.
builder.Host.ConfigureContainer<ContainerBuilder>(builder...
var app = builder.Build();
}}
*** 添加中间件 [#ndd26a13]
中间件的添加都应该在WebApplication上完成
#codeprettify{{
var app = WebApplication.Create(args);
// Setup the file server to serve static files
app.UseFileServer();
app.Run();
}}
*** 开发的错误页面 [#q36c784c]
WebApplication默认启用了开发者异常页面
#codeprettify{{
var app = WebApplication.Create(args);
app.MapGet("/", () => throw new InvalidOperationException...
app.Run();
}}
#hr();
コメント:
#comment_kcaptcha
}}
終了行:
[[ASP.NET Core Web]]
&color(red){※This article is based on .NET 7};
#contents
* 概要 [#w9a1afa4]
标准提供 WebApplication 和 WebApplicationBuilder 两个类,...
- WebApplicaiton代表的是运行的应用
- ApplicationBuilder 意味着由它构建的就是一个Application...
那么在ASP.NET Core框架的语义下应用(Application)可以这样...
那么HttpHandler就等于Application,由于HttpHandler通过Requ...
由于表示HttpHandler的RequestDelegate是由注册的中间件来构...
#codeprettify{{
public interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, Request...
RequestDelegate Build();
}
}}
如下所示的是针对该接口的具体实现。我们利用一个列表来保存...
#codeprettify{{
public class ApplicationBuilder : IApplicationBuilder
{
private readonly List<Func<RequestDelegate, RequestDe...
public RequestDelegate Build()
{
_middlewares.Reverse();
return httpContext =>
{
RequestDelegate next = _ => { _.Response.Stat...
foreach (var middleware in _middlewares)
{
next = middleware(next);
}
return next(httpContext);
};
}
public IApplicationBuilder Use(Func<RequestDelegate, ...
{
_middlewares.Add(middleware);
return this;
}
}
}}
在调用第一个中间件(最后注册)的时候,我们创建了一个Reque...
** 标准默认做法 [#xa976650]
Startup.cs
#codeprettify{{
namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use th...
public void ConfigureServices(IServiceCollection ...
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Titl...
});
}
// This method gets called by the runtime. Use th...
public void Configure(IApplicationBuilder app, IW...
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("...
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
}}
* 极简代码 [#cafd5c2a]
通过代码来配置
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Configure the cert and the key
builder.Configuration["Kestrel:Certificates:Default:Path"...
builder.Configuration["Kestrel:Certificates:Default:KeyPa...
var app = builder.Build();
app.Urls.Add("https://localhost:3000");
app.MapGet("/", () => "Hello World");
app.Run();
}}
* 配置 [#j3f28966]
** 改变应用content root, app name以及环境变量 [#pc9169a8]
#codeprettify{{
var builder = WebApplication.CreateBuilder(new WebApplica...
{
ApplicationName = typeof(Program).Assembly.FullName,
ContentRootPath = Directory.GetCurrentDirectory(),
EnvironmentName = Environments.Staging
});
Console.WriteLine($"Application Name: {builder.Environmen...
Console.WriteLine($"Environment Name: {builder.Environmen...
Console.WriteLine($"ContentRoot Path: {builder.Environmen...
var app = builder.Build();
}}
运行后:
#codeprettify{{
:\MyProjects\DotNetLearning\.Net6\WebApplicationDemo>dotn...
正在生成...
Application Name: WebApplicationDemo, Version=1.0.0.0, Cu...
Environment Name: Staging
ContentRoot Path: D:\MyProjects\DotNetLearning\.Net6\WebA...
}}
除了代码改变之外,还可以通过如下的环境变量来改变:
- ASPNETCORE_ENVIRONMENT
- ASPNETCORE_CONTENTROOT
- ASPNETCORE_APPLICATIONNAME
或者通过命令行参数来改变:
- --applicationName
- --environment
- --contentRoot
** 配置项 [#rf6a9fc1]
*** 添加配置source [#mab44dac]
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddIniFile("appsettings.ini");
var app = builder.Build();
}}
读取配置
默认按照如下的顺序读取配置:
+ appSettings.json
+ appSettings.{environment}.json
+ environment variables
+ 命令行参数
*** 读取配置 [#v24d3b22]
读取配置的实例:
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Reads the ConnectionStrings section of configuration a...
var connectionString = builder.Configuration.GetConnectio...
Console.WriteLine($"My connection string is {connectionSt...
var app = builder.Build();
}}
appsettings.json的内容
#codeprettify{{
{
"cnblogs": "My CNBlogs Address:https://www.cnb.com",
"AppSettings": {
"HttpUrl": "http://www.gt.com",
"Copyright": "gzbit"
},
"Person": [
{
"name": "xfmtl",
"company": "gzbit",
"address": [
{
"province": "Guizhou Province",
"city": "Guiyang City"
},
{
"province": "Yunnan Province",
"city": "Wuhua District"
}
]
},
{
"name": "C# Study",
"adress": "Microsoft"
}
],
"Book": {
"name": "C# Program",
"publish": "2020-08"
}
}
}}
Controller里读取配置的实例:
#codeprettify{{
public IActionResult Index()
{
//加载配置文件
ConfigurationBuilder configurationBuilder = new Confi...
//添加配置文件路径
configurationBuilder.SetBasePath(Directory.GetCurrent...
.AddJsonFile("appsettings.json");
var configuration = configurationBuilder.Build();
//获取博客园地址
var cnblogs = configuration["cnblogs"];
//获取Book名称
var bookname = configuration.GetValue<string>("Book:n...
//获取幸福摩天轮的第一地区名称
var addressName = configuration.GetValue<string>("Per...
//获取C# 学习的名称
var cname = configuration.GetValue<string>("Person:1:...
//获取所在公司
var companyName= configuration["AppSettings:Copyright...
return Content(cnblogs);
}
}}
*** 读取环境变量 [#rc3d0ba1]
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
Console.WriteLine($"Running in development");
}
var app = builder.Build();
}}
*** 添加日志配置 [#fb363e5f]
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Configure JSON logging to the console
builder.Logging.AddJsonConsole();
var app = builder.Build();
}}
*** 添加Service [#ub8efc2d]
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Add the memory cache services
builder.Services.AddMemoryCache();
// Add a custom scoped service
builder.Services.AddScoped<ITodoRepository, TodoRepositor...
var app = builder.Build();
}}
*** 改变webroot [#r8da6aca]
默认情况下webroot是在相对路径下的wwwroot下,如果要改变这...
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
// Look for static files in webroot
builder.WebHost.UseWebRoot("webroot");
var app = builder.Build();
}}
*** 定制DI容器 [#de11d13e]
我们这里使用Autofac
#codeprettify{{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacService...
// Register your own things directly with Autofac here. D...
// call builder.Populate(), that happens in AutofacServic...
// for you.
builder.Host.ConfigureContainer<ContainerBuilder>(builder...
var app = builder.Build();
}}
*** 添加中间件 [#ndd26a13]
中间件的添加都应该在WebApplication上完成
#codeprettify{{
var app = WebApplication.Create(args);
// Setup the file server to serve static files
app.UseFileServer();
app.Run();
}}
*** 开发的错误页面 [#q36c784c]
WebApplication默认启用了开发者异常页面
#codeprettify{{
var app = WebApplication.Create(args);
app.MapGet("/", () => throw new InvalidOperationException...
app.Run();
}}
#hr();
コメント:
#comment_kcaptcha
}}
ページ名: