一步一步遷移ASP.NET Core 6.0-Part1

Eric zhou發表於2022-03-21

.NET 6 釋出後,我們現有的應用會逐步升級到這個版本,首當其衝的是原因的ASP.NET Core的工程,如果一步一步升級到ASP.NET Core 6.0

本文簡單整理一下升級ASP.NET Core 6.0的一些常用程式碼示例。

一、中介軟體升級

   原有新增靜態檔案中介軟體的程式碼:

   升級ASP.NET Core 6.0的程式碼實現:

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

app.UseStaticFiles();

app.Run();

二、新增終結點路由

   原有新增終結點路由的方式

升級ASP.NET Core 6.0的程式碼實現:

可以直接將路由新增到 WebApplication,而無需顯式呼叫 UseEndpoints 或 UseRouting

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

app.MapGet("/", () => "ASP.NET6!");

app.Run();

三、內容根、應用名稱和環境

    原有程式碼中內容根、應用名稱和環境的設定方式:

 

   升級ASP.NET Core 6.0的程式碼實現:

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

 

 

  可以按環境變數或命令列更改內容根、應用程式名稱和環境,

  以下顯示了用於更改內容根、應用程式名稱和環境的環境變數及命令列引數:

 

 四、新增配置提供程式

  原先ASP.NET Core 5.0 新增配置提供程式的程式碼實現,以Ini配置檔案為例:

  

  升級ASP.NET Core 6.0的程式碼實現:

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddIniFile("appsettings.ini");

var app = builder.Build();

 

 五、新增日誌記錄提供程式

    原先ASP.NET Core 5.0 新增日誌記錄提供程式的程式碼實現

    升級ASP.NET Core 6.0的程式碼實現:

var builder = WebApplication.CreateBuilder(args);

// Configure JSON logging to the console.
builder.Logging.AddJsonConsole();

var app = builder.Build();

 

 六、DI依賴注入管理新增、註冊服務

   原先ASP.NET Core 5.0 新增一個服務的實現方式:

 

       升級ASP.NET Core 6.0的程式碼實現:

var builder = WebApplication.CreateBuilder(args);

// Add the memory cache services.
builder.Services.AddMemoryCache();

// Add a custom scoped service.
builder.Services.AddScoped<IOrderService, OrderServiceRepository>();
var app = builder.Build();

 

 

 遷移ASP.NET Core 6.0涉及到的內容還有一些,將在下一篇文章中陸續增加。

 

周國慶

2022/3/21

 

相關文章