Sampel kode dimigrasikan ke model hosting minimal baru di ASP.NET Core 6.0
Artikel ini menyediakan sampel kode yang dimigrasikan ke ASP.NET Core 6.0. ASP.NET Core 6.0 menggunakan model hosting minimal baru. Untuk informasi selengkapnya, lihat Model hosting baru.
Middleware
Kode berikut menambahkan Middleware File Statis ke aplikasi ASP.NET Core 5:
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
}
Kode berikut menambahkan Middleware File Statis ke aplikasi ASP.NET Core 6:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseStaticFiles();
app.Run();
WebApplication.CreateBuilder menginisialisasi instans baru kelas WebApplicationBuilder dengan default yang telah dikonfigurasi sebelumnya. Untuk informasi selengkapnya, lihat ASP.NET Core Middleware
Perutean
Kode berikut menambahkan titik akhir ke aplikasi ASP.NET Core 5:
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", () => "Hello World");
});
}
}
Di .NET 6, rute dapat ditambahkan langsung ke WebApplication tanpa panggilan eksplisit ke UseEndpoints atau UseRouting. Kode berikut menambahkan titik akhir ke aplikasi ASP.NET Core 6:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Catatan: Rute yang ditambahkan langsung ke WebApplication eksekusi di akhir alur.
Mengubah akar konten, nama aplikasi, dan lingkungan
ASP.NET Core 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();
Untuk informasi selengkapnya, lihat gambaran umum dasar-dasar ASP.NET Core
Mengubah akar konten, nama aplikasi, dan lingkungan menurut variabel lingkungan atau baris perintah
Tabel berikut ini memperlihatkan variabel lingkungan dan argumen baris perintah yang digunakan untuk mengubah akar konten, nama aplikasi, dan lingkungan:
fitur | Variabel lingkungan | Argumen baris perintah |
---|---|---|
Nama aplikasi | ASPNETCORE_APPLICATIONNAME | --applicationName |
Nama lingkungan | ASPNETCORE_ENVIRONMENT | --Lingkungan |
Akar konten | ASPNETCORE_CONTENTROOT | --contentRoot |
Menambahkan penyedia konfigurasi
ASP.NET Core 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();
Untuk informasi terperinci, lihat Penyedia konfigurasi file di Konfigurasi di ASP.NET Core.
Menambahkan penyedia pengelogan
ASP.NET Core 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();
Untuk informasi selengkapnya, lihat Pengelogan .NET Core dan ASP.NET Core.
Menambahkan layanan
ASP.NET Core 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();
Untuk informasi lebih lanjut, lihat Injeksi dependensi di ASP.NET Core.
Menyesuaikan IHostBuilder atau IWebHostBuilder
Menyesuaikan IHostBuilder
ASP.NET Core 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();
Menyesuaikan IWebHostBuilder
ASP.NET Core 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();
Mengubah akar web
Secara default, akar web relatif terhadap akar konten di wwwroot
folder. Akar web adalah tempat middleware file statis mencari file statis. Akar web dapat diubah dengan mengatur WebRootPath properti pada WebApplicationOptions:
ASP.NET Core 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();
Kontainer injeksi dependensi kustom (DI)
Sampel .NET 5 dan .NET 6 berikut menggunakan Autofac
ASP.NET Core 5
Kelas program
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
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();
Mengakses layanan tambahan
Startup.Configure
dapat menyuntikkan layanan apa pun yang IServiceCollectionditambahkan melalui .
ASP.NET Core 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
Di ASP.NET Core 6:
- Ada beberapa layanan umum yang tersedia sebagai properti tingkat atas di WebApplication.
- Layanan tambahan perlu diselesaikan secara manual dari
IServiceProvider
melalui WebApplication.Services.
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}"));
Uji dengan WebApplicationFactory atau TestServer
ASP.NET Core 5
Dalam sampel berikut, proyek pengujian menggunakan TestServer
dan WebApplicationFactory<TEntryPoint>. Pengiriman ini sebagai paket terpisah yang memerlukan referensi eksplisit:
WebApplicationFactory
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="{Version}" />
</ItemGroup>
TestServer
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="{Version}" />
</ItemGroup>
kode 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);
});
});
}
}
Dengan 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";
}
Dengan 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();
File proyek (.csproj)
File proyek dapat berisi salah satu hal berikut:
<ItemGroup>
<InternalsVisibleTo Include="MyTestProject" />
</ItemGroup>
Atau
[assembly: InternalsVisibleTo("MyTestProject")]
Solusi alternatifnya adalah membuat kelas menjadi Program
publik. Program
dapat dipublikasikan dengan pernyataan tingkat atas dengan mendefinisikan public partial Program
kelas dalam proyek atau di Program.cs
:
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";
}
Versi .NET 5 dan versi .NET 6 dengan WebApplicationFactory
identik menurut desain.
ASP.NET Core