ASP.NET Core 的 WebApplication 类和 WebApplicationBuilder 类

原文链接:https://blog.csdn.net/cuit/article/details/132504757

WebApplication 类
ASP.NET Core 有3个 Host 类,是ASP.NET Core中用于初始化,生命周期管理,启动Web 服务的最重要的类。所以详细重点分析一下这几个类,分别是:

WebApplication,ASP.NET Core 6 引入的替代WebHost的类,可以用于 Web App或者 Web API
Host,非 Web App或者Web API 使用的 Host 类,比如纯控制台,或者 Windows Service。
WebHost,ASP.NET Core 6之前的版本使用的Host类。此处不再学习。


2个静态方法
CreateBuilder(),用于创建WebApplicationBuilder 对象,再用 Build 模式添加一些中间件,再创建WebApplication对象。
Create(),用于直接创建一个WebApplication对象,会默认添加和配置一些中间件。

使用CreateBuilder的例子代码:

1
2
3
4
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();

直接创建一个WebApplication对象的例子代码:

1
2
3
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();

然后再用 Run()方法启动Web服务。包括 Run(),共有3个方法启动Web服务,区别是:

Run(),阻塞当前线程,直到 Host 关闭。
RunAsync(),启动 Host 的 Task,只有当 token 或者 shutdown 被触发时才会完成此。
StartAsync(),启动 Host的 Task,启动成功后立即返回 Task,然后 HTTP Server 可以接收 HTTP Request 。

其他的扩展方法
UseRequestLocalization(),使用 RequestLocalizationMiddleware 中间件,根据客户端的 http 请求自动设置语言。
UseAuthentication(),使用 AuthenticationMiddleware 中间件,开启身份验证功能。
UseAuthorization(),使用 AuthorizationMiddleware 中间件,开启权限验证功能,必须用于app.UseRouting() 与 app.UseEndpoints(…)之间。
UseCertificateForwarding(),验证来自客户端请求的 Header 中的证书,然后更新在HttpContext.Connection.ClientCertificate中。
UseConcurrencyLimiter(),使用ConcurrencyLimiterMiddleware 中间件,限制并发请求数。
MapConnectionHandler(),将特定路径的请求映射到某个 pipeline。
MapConnections(),同上。
MapAreaControllerRoute(),为controller映射endpoints,并指定路由。
MapControllers(),为controllerr映射endpoints,但不指定路由。
MapDefaultControllerRoute(),为controllerr映射endpoints,并使用默认路由{controller=Home}/{action=Index}/{id?}。
MapDynamicControllerRoute(),为controllerr映射特定的 Route endpoints
MapFallbackToAreaController(),为controllerr映射特定的 Route endpoints
UseCookiePolicy(),使用CookiePolicyMiddleware 中间件,开启 Cookie策略功能。
UseCors(),使用CORS中间件,开启跨域功能。
UseDefaultFiles(),开启默认的文件映射功能。
UseDeveloperExceptionPage(),在开发环境下生成 exception 的 htmld页面。
UseDirectoryBrowser(),开启目录浏览功能。
UseFileServer(),使用静态文件中间件,映射request 路径到我们预设的其他路径,但不包含DirectoryBrowser功能。
UseStaticFiles(),使用静态文件中间件。
Map(),模式匹配 HTTP 请求,映射到某个endpoint。
MapHub(),模式匹配 HTTP 请求,映射到某个Hub。
MapDelete(),模式匹配 HTTP Delete请求,映射到某个endpoint。
MapGet(),模式匹配 HTTP Get请求,映射到某个endpoint。
MapPut(),模式匹配 HTTP Put请求,映射到某个endpoint。
MapPost(),模式匹配 HTTP Post请求,映射到某个endpoint。
MapGroup(),模式匹配 某个前缀的HTTP 请求,映射到某个endpoint。
MapMethods(),模式匹配 某个方法的HTTP 请求,映射到某个endpoint。
MapPatch(),模式匹配 HTTP Patch 请求,映射到某个endpoint。
MapHealthChecks(),使用某个endpoint提供的HealthChecks功能。
UseEndpoints(),使用Endpoints中间件,指定endpoints。
UseRouting(),使用路由中间件。
UseExceptionHandler(),捕获异常,记录,如果还没有执行 response,则再用预设的另一个 pipeline 执行一次,
UseForwardedHeaders(),HTTP代理转发client request 的 header,填充HttpContext。
UseHeaderPropagation(),收集header,发给 HttpClient。
UseHealthChecks(),使用健康度检查中间件。
UseHostFiltering(),过滤 http 请求,无效请求返回400。
UseHsts(),使用HSTS,添加Strict-Transport-Security header。
UseHttpLogging(),记录 http的 request 和 response。
UseW3CLogging(),以 W3C 格式记录 http的 request 和 response。
UseHttpMethodOverride(),当限制 client 的 GET或 POST 请求时,可执行其他请求。
UseHttpsRedirection(),将 http 请求重定向至 https。
UseMigrationsEndPoint(),侦听DefaultPath的请求,然后执行migrations操作。
UseMvc(),使用MVC中间件。
UseOutputCache(),caching HTTP response。
UseResponseCaching(),aching HTTP response。
UseOwin(),使用Owin。
UseRateLimiter(),限制requests流量。
UseRequestDecompression(), 解压缩 HTTP request功能。
UseResponseCompression(), 解压缩 HTTP response功能。
UseRewriter(),重写某个 url,修改HttpContext。
UseRouter(),
UseSession(),启用 Session功能。
UseSpa(),返回SPA的默认页面。
UseSpaStaticFiles(),在 SPA 中使用静态文件。
UseStatusCodePages(),当没有 body 时,返回400 and 599。
UseMiddleware(),使用自定义中间件。
UsePathBase(),提取路径
UseWebSockets(),使用WebSockets。
UseWelcomePage(),使用WelcomePage。
6个关键属性
Configuration,
Environment,
Lifetime
Logger
Services
Urls

Services
注册使用Service:

1
2
3
4
5
6
var builder = WebApplication.CreateBuilder(args);
// Add the memory cache services.
builder.Services.AddMemoryCache();
// Add a custom scoped service.
builder.Services.AddScoped<ITodoRepository, TodoRepository>();
var app = builder.Build();

  

posted @   yinghualeihenmei  阅读(143)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-06-21 Global.asax文件
点击右上角即可分享
微信分享提示