You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何迁移ASP.NET WebHost Builder至.NET6,规避ASP0009并替代Configure()

解决.NET 6/7中ASP0009错误及UseEndPoints替代方案

问题原因

builder.WebHost.Configure属于.NET 6之前的旧配置模式,在新的WebApplication模型中已被弃用,因此编译器抛出ASP0009警告。新模型将服务配置与中间件管道配置拆分,中间件管道需在WebApplication实例(即builder.Build()的返回值)上配置,而非在WebApplicationBuilder阶段通过WebHost操作。

解决方案

你需要将中间件配置逻辑从builder.WebHost.Configure中移出,先在builder阶段完成服务注册,保留builder实例用于后续配置,待所有配置完成后调用Build()得到WebApplication,再在其上配置中间件和路由。

第一步:保留builder并完成服务配置

var builder = WebApplication.CreateBuilder();

// 注册控制器服务(必须添加,否则路由映射无效)
builder.Services.AddControllers();

// 在此添加其他后续需要的配置,比如认证服务、数据库上下文等
// builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
//     .AddJwtBearer(...);

return builder;

第二步:完成所有配置后,构建WebApplication并配置中间件

当你完成所有builder层面的配置后,调用Build(),然后用以下方式替代原UseEndPoints逻辑:

var app = builder.Build();

// 配置中间件管道
app.UseRouting();
app.UseAuthentication();

// 替代UseEndPoints的写法:直接调用MapDefaultControllerRoute
app.MapDefaultControllerRoute();

// 若需自定义控制器路由,可改用:
// app.MapControllers();

app.Run();

关键说明

  • .MapDefaultControllerRoute()等价于原UseEndPoints中_.MapDefaultControllerRoute()的逻辑,是.NET 6+提供的简化写法,无需再嵌套在UseEndPoints内。
  • 所有服务注册(如AddControllers、AddAuthentication)必须在builder.Build()之前完成,而中间件(UseRouting、UseAuthentication等)必须在Build()之后的WebApplication实例上配置。

内容的提问来源于stack exchange,提问作者stb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:01:15