Artikel ini memberikan contoh kode yang dimigrasikan ke ASP.NET Core 6.0. ASP.NET Core 6.0 menggunakan model hosting minimal baru. Untuk informasi lebih lanjut, lihat Model hosting baru.

Middleware

Kode berikut menambahkan Static File Middleware ke aplikasi ASP.NET Core 5:

public class Startup

    public void Configure(IApplicationBuilder app)
    
        app.UseStaticFiles();
    

Kode berikut menambahkan Static File Middleware ke aplikasi ASP.NET Core 6:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseStaticFiles();

app.Run();

WebApplication.CreateBuilder menginisialisasi instance baru dari kelas WebApplicationBuilder dengan default yang telah dikonfigurasi sebelumnya. Untuk informasi lebih lanjut, lihat ASP.NET Core Middleware

Rute

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 Aplikasi Web 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 dijalankan di akhir dari pipa.

Ubah root konten, nama aplikasi, dan lingkungan

ASP.NET Inti 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

    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();

Ubah root konten, nama aplikasi, dan lingkungan dengan variabel lingkungan atau baris perintah

Tabel berikut menunjukkan variabel lingkungan dan argumen baris perintah yang digunakan untuk mengubah root konten, nama aplikasi, dan lingkungan:

fitur Variabel lingkungan Argumen baris perintah
Nama aplikasi ASPNETCORE_APPLICATIONNAME –nama aplikasi
Nama lingkungan ASPNETCORE_ENVIRONMENT –lingkungan
Akar konten ASPNETCORE_CONTENTROOT –contentRoot

Tambahkan penyedia konfigurasi

ASP.NET Inti 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 mendetail, lihat Penyedia konfigurasi file di Konfigurasi di ASP.NET Core.

Tambahkan penyedia logging

ASP.NET Inti 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 Masuk ke .NET Core dan ASP.NET Core.

Tambahkan layanan

ASP.NET Inti 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 selengkapnya, lihat Injeksi ketergantungan di ASP.NET Core.

Sesuaikan IHostBuilder atau IWebHostBuilder

Sesuaikan IHostBuilder

ASP.NET Inti 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();

Sesuaikan IWebHostBuilder

ASP.NET Inti 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();

Ubah root web

Secara default, root web relatif terhadap root konten di wwwroot map. Akar web adalah tempat middleware file statis mencari file statis. Akar web dapat diubah dengan menyetel properti WebRootPath di WebApplicationOptions:

ASP.NET Inti 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();

Wadah injeksi ketergantungan khusus (DI)

Contoh .NET 5 dan .NET 6 berikut menggunakan Autofac

ASP.NET Inti 5

Kelas program

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseServiceProviderFactory(new AutofacServiceProviderFactory())
        .ConfigureWebHostDefaults(webBuilder =>
        
            webBuilder.UseStartup<Startup>();
        );

Memulai

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();

Akses layanan tambahan

Startup.Configure dapat menyuntikkan layanan apa pun yang ditambahkan melalui IServiceCollection.

ASP.NET Inti 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 env.ApplicationName started" +
                                  $" in the injected service"));
    

ASP.NET Core 6

Di ASP.NET Inti 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 Inti 5

Dalam contoh berikut, proyek uji menggunakan TestServer dan WebApplicationFactory. Kapal ini sebagai paket terpisah yang memerlukan referensi eksplisit:

WebAplikasiPabrik

<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 dari berikut ini:

<ItemGroup>
    <InternalsVisibleTo Include="MyTestProject" />
</ItemGroup>

Atau

[assembly: InternalsVisibleTo("MyTestProject")]

Solusi alternatif adalah dengan membuat Program publik kelas. Program dapat dipublikasikan dengan pernyataan tingkat atas dengan mendefinisikan a 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 dengan desain.

By AKDSEO