.NET 6新特性试用 | 无需配置开发人员异常页
Posted dotNET跨平台
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET 6新特性试用 | 无需配置开发人员异常页相关的知识,希望对你有一定的参考价值。
前言
在.NET 6之前,我们需要在“Startup.cs”文件中手工配置开发人员异常页:
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication5 v1"));
如果当前环境变量ASPNETCORE_ENVIRONMENT
的值是“Development”,将显示未经处理的请求异常的详细信息:
在.NET 6中,我们发现,无需显式调用UseDeveloperExceptionPage
,开发人员异常页同样起作用。
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
app.UseSwagger();
app.UseSwaggerUI();
为什么呢?
原理探究
在https://github.com/dotnet/aspnetcore/blob/main/src/DefaultBuilder/src/WebApplicationBuilder.cs中,我们找到如下代码:
private void ConfigureApplication(WebHostBuilderContext context, IApplicationBuilder app)
......
if (context.HostingEnvironment.IsDevelopment())
app.UseDeveloperExceptionPage();
......
internal WebApplicationBuilder(WebApplicationOptions options, Action<IHostBuilder>? configureDefaults = null)
......
_bootstrapHostBuilder.ConfigureWebHostDefaults(webHostBuilder =>
// Runs inline.
webHostBuilder.Configure(ConfigureApplication);
// Attempt to set the application name from options
options.ApplyApplicationName(webHostBuilder);
);
......
原来是在构造函数进行了默认处理,也就是在API实现的第一句代码中执行的;
var builder = WebApplication.CreateBuilder(args);
// Microsoft.AspNetCore.Builder.WebApplication
public static WebApplicationBuilder CreateBuilder(string[] args)
return new WebApplicationBuilder(new WebApplicationOptions
Args = args
);
那.NET 6还帮我们默认做了哪些事呢?
其他默认操作
继续查看ConfigureApplication
实现,可以发现.NET 6还进行了其他默认处理,比如:
UseRouting
// If this is set, someone called UseRouting() when a global route builder was already set
if (!_builtApplication.Properties.TryGetValue(EndpointRouteBuilderKey, out var localRouteBuilder))
app.UseRouting();
else
// UseEndpoints will be looking for the RouteBuilder so make sure it's set
app.Properties[EndpointRouteBuilderKey] = localRouteBuilder;
而在.NET 5中必须手工配置,否则报错:
UseEndpoints
if (_builtApplication.DataSources.Count > 0)
// We don't know if user code called UseEndpoints(), so we will call it just in case, UseEndpoints() will ignore duplicate DataSources
app.UseEndpoints(_ => );
而在.NET 5中必须在UseEndpoints
方法中才能执行MapXXX方法
:
app.UseEndpoints(endpoints =>
endpoints.MapGet("/", async context =>
await context.Response.WriteAsync("Hello My IO!");
);
);
结论
正是因为.NET 6内部帮我们做了大量工作,才使得实现最小Web API成为可能:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
减少初始代码量,这对新手入门无疑是更友好的!
如果你觉得这篇文章对你有所启发,请帮忙点个赞或者在看
以上是关于.NET 6新特性试用 | 无需配置开发人员异常页的主要内容,如果未能解决你的问题,请参考以下文章