前言
在.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 optionsoptions.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 setapp.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 DataSourcesapp.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();
减少初始代码量,这对新手入门无疑是更友好的!
如果你觉得这篇文章对你有所启发,请帮忙点个赞或者在看