迁移到 ASP.NET Core 6.0 中新的最小托管模型的代码示例
本文提供了迁移到 ASP.NET Core 6.0 的代码示例。 ASP.NET Core 6.0 使用新的最小托管模型。 有关详细信息,请参阅新托管模型。
中间件
以下代码将静态文件中间件添加到 ASP.NET Core 5 应用:
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
}
以下代码将静态文件中间件添加到 ASP.NET Core 6 应用:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseStaticFiles();
app.Run();
WebApplication.CreateBuilder 使用预配置的默认值初始化 WebApplicationBuilder 类的新实例。 有关详细信息,请参阅 ASP.NET Core 中间件
路由
以下代码将终结点添加到 ASP.NET Core 5 应用:
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", () => "Hello World");
});
}
}
在 .NET 6 中,可以直接将路由添加到 WebApplication,而无需显式调用 UseEndpoints 或 UseRouting。 以下代码将终结点添加到 ASP.NET Core 6 应用:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
注意:直接添加到 WebApplication 的路由在管道的末端执行。
更改内容根、应用名称和环境
ASP.NET 核心 5
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseEnvironment(Environments.Staging)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseSetting(WebHostDefaults.ApplicationKey,
typeof(Program).Assembly.FullName);
});
ASP.NET Core 6
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ApplicationName = typeof(Program).Assembly.FullName,
ContentRootPath = Directory.GetCurrentDirectory(),
EnvironmentName = Environments.Staging,
WebRootPath = "customwwwroot"
});
Console.WriteLine($"Application Name: {builder.Environment.ApplicationName}");
Console.WriteLine($"Environment Name: {builder.Environment.EnvironmentName}");
Console.WriteLine($"ContentRoot Path: {builder.Environment.ContentRootPath}");
Console.WriteLine($"WebRootPath: {builder.Environment.WebRootPath}");
var app = builder.Build();
有关详细信息,请参阅 ASP.NET Core 基础知识概述
按环境变量或命令行更改内容根、应用程序名称和环境
下表显示了用于更改内容根、应用程序名称和环境的环境变量及命令行参数:
feature | 环境变量 | 命令行参数 |
---|---|---|
应用程序名称 | ASPNETCORE_APPLICATIONNAME | --applicationName |
环境名称 | ASPNETCORE_ENVIRONMENT | --environment |
内容根 | ASPNETCORE_CONTENTROOT | --contentRoot |
添加配置提供程序
ASP.NET 核心 5
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config =>
{
config.AddIniFile("appsettings.ini");
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
ASP.NET Core 6
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddIniFile("appsettings.ini");
var app = builder.Build();
有关详细信息,请参阅 ASP.NET Core 中的配置中的文件配置提供程序。
添加日志记录提供程序
ASP.NET 核心 5
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.AddJsonConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
ASP.NET Core 6
var builder = WebApplication.CreateBuilder(args);
// Configure JSON logging to the console.
builder.Logging.AddJsonConsole();
var app = builder.Build();
有关详细信息,请参阅 .NET Core 和 ASP.NET Core 中的日志记录。
添加服务
ASP.NET 核心 5
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add the memory cache services
services.AddMemoryCache();
// Add a custom scoped service
services.AddScoped<ITodoRepository, TodoRepository>();
}
}
ASP.NET Core 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();
有关详细信息,请参阅 ASP.NET Core 中的依赖项注入。
自定义 IHostBuilder 或 IWebHostBuilder
自定义 IHostBuilder
ASP.NET 核心 5
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
ASP.NET Core 6
var builder = WebApplication.CreateBuilder(args);
// Wait 30 seconds for graceful shutdown.
builder.Host.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
var app = builder.Build();
自定义 IWebHostBuilder
ASP.NET 核心 5
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
// Change the HTTP server implementation to be HTTP.sys based.
webBuilder.UseHttpSys()
.UseStartup<Startup>();
});
ASP.NET Core 6
var builder = WebApplication.CreateBuilder(args);
// Change the HTTP server implementation to be HTTP.sys based.
// Windows only.
builder.WebHost.UseHttpSys();
var app = builder.Build();
更改 Web 根
默认情况下,Web 根相对于 wwwroot
文件夹中的内容根。 Web 根是静态文件中间件查找静态文件的位置。 通过设置 WebApplicationOptions 上的 WebRootPath 属性,可以更改 Web 根:
ASP.NET 核心 5
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
// Look for static files in webroot.
webBuilder.UseWebRoot("webroot")
.UseStartup<Startup>();
});
ASP.NET Core 6
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
// Look for static files in webroot
WebRootPath = "webroot"
});
var app = builder.Build();
自定义依赖项注入 (DI) 容器
以下 .NET 5 和 .NET 6 示例使用 Autofac
ASP.NET 核心 5
Program 类
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
启动
public class Startup
{
public void ConfigureContainer(ContainerBuilder containerBuilder)
{
}
}
ASP.NET Core 6
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// Register services directly with Autofac here. Don't
// call builder.Populate(), that happens in AutofacServiceProviderFactory.
builder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new MyApplicationModule()));
var app = builder.Build();
访问其他服务
Startup.Configure
可以注入通过 IServiceCollection 添加的任何服务。
ASP.NET 核心 5
public class Startup
{
// This method gets called by the runtime. Use this method to add services
// to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IService, Service>();
}
// Anything added to the service collection can be injected into Configure.
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IHostApplicationLifetime lifetime,
IService service,
ILogger<Startup> logger)
{
lifetime.ApplicationStarted.Register(() =>
logger.LogInformation(
"The application {Name} started in the injected {Service}",
env.ApplicationName, service));
}
}
ASP.NET Core 6
在 ASP.NET Core 6 中:
- 有一些通用服务可用作 WebApplication 上的顶级属性。
- 其他服务需要通过 WebApplication.Services 从
IServiceProvider
手动解析。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IService, Service>();
var app = builder.Build();
IService service = app.Services.GetRequiredService<IService>();
ILogger logger = app.Logger;
IHostApplicationLifetime lifetime = app.Lifetime;
IWebHostEnvironment env = app.Environment;
lifetime.ApplicationStarted.Register(() =>
logger.LogInformation(
$"The application {env.ApplicationName} started" +
$" with injected {service}"));
使用 WebApplicationFactory 或 TestServer 进行测试
ASP.NET 核心 5
在以下示例中,测试项目使用 TestServer
和 WebApplicationFactory<TEntryPoint>。 它们作为需要显式引用的独立包提供:
WebApplicationFactory
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="{Version}" />
</ItemGroup>
TestServer
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="{Version}" />
</ItemGroup>
ASP.NET Core 5 代码
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHelloService, HelloService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHelloService helloService)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync(helloService.HelloMessage);
});
});
}
}
使用 TestServer
[Fact]
public async Task HelloWorld()
{
using var host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(builder =>
{
// Use the test server and point to the application's startup
builder.UseTestServer()
.UseStartup<WebApplication1.Startup>();
})
.ConfigureServices(services =>
{
// Replace the service
services.AddSingleton<IHelloService, MockHelloService>();
})
.Build();
await host.StartAsync();
var client = host.GetTestClient();
var response = await client.GetStringAsync("/");
Assert.Equal("Test Hello", response);
}
class MockHelloService : IHelloService
{
public string HelloMessage => "Test Hello";
}
使用 WebApplicationFactory
[Fact]
public async Task HelloWorld()
{
var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IHelloService, MockHelloService>();
});
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/");
Assert.Equal("Test Hello", response);
}
class MockHelloService : IHelloService
{
public string HelloMessage => "Test Hello";
}
ASP.NET Core 6
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IHelloService, HelloService>();
var app = builder.Build();
var helloService = app.Services.GetRequiredService<IHelloService>();
app.MapGet("/", async context =>
{
await context.Response.WriteAsync(helloService.HelloMessage);
});
app.Run();
项目文件 (.csproj)
项目文件可以包含以下内容之一:
<ItemGroup>
<InternalsVisibleTo Include="MyTestProject" />
</ItemGroup>
或
[assembly: InternalsVisibleTo("MyTestProject")]
另一种解决方案是公开 Program
类。 通过在项目或 Program.cs
中定义 public partial Program
类,可以使用顶级语句公开 Program
:
var builder = WebApplication.CreateBuilder(args);
// ... Configure services, routes, etc.
app.Run();
public partial class Program { }
[Fact]
public async Task HelloWorld()
{
var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IHelloService, MockHelloService>();
});
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/");
Assert.Equal("Test Hello", response);
}
class MockHelloService : IHelloService
{
public string HelloMessage => "Test Hello";
}
使用 WebApplicationFactory
的 .NET 5 版本和 .NET 6 版本在设计上是相同的。