Nguon: Microsoft Learn · .NET 8.0

IActionContextAccessor và ActionContextAccessor đã lỗi thời (obsolete)

Nguồn: IActionContextAccessor and ActionContextAccessor are obsolete

IActionContextAccessorActionContextAccessor đã được đánh dấu là obsolete (lỗi thời) với ID chẩn đoán ASPDEPR006. Với sự ra đời của endpoint routing (định tuyến theo endpoint), IActionContextAccessor không còn cần thiết vì các nhà phát triển có thể truy cập thông tin action descriptor và metadata trực tiếp thông qua HttpContext.GetEndpoint().

Phiên bản được giới thiệu

.NET 10 Preview 7

Hành vi trước đây

Trước đây, bạn có thể dùng IActionContextAccessor để truy cập ActionContext hiện tại:

csharp
public class MyService
{
   private readonly IActionContextAccessor _actionContextAccessor;

   public MyService(IActionContextAccessor actionContextAccessor)
   {
       _actionContextAccessor = actionContextAccessor;
   }

   public void DoSomething()
   {
       var actionContext = _actionContextAccessor.ActionContext;
       var actionDescriptor = actionContext?.ActionDescriptor;
       // Sử dụng action descriptor metadata.
   }
}

Hành vi mới

Bắt đầu từ .NET 10, việc sử dụng IActionContextAccessorActionContextAccessor sẽ tạo ra cảnh báo compiler với ID chẩn đoán ASPDEPR006:

warning ASPDEPR006: ActionContextAccessor is obsolete and will be removed in a future version. For more information, visit https://aka.ms/aspnet/deprecate/006.

Loại thay đổi có thể gây lỗi

Thay đổi này có thể ảnh hưởng đến source compatibility (tương thích mã nguồn).

Lý do thay đổi

Với sự ra đời của endpoint routing trong ASP.NET Core, IActionContextAccessor không còn cần thiết nữa. Cơ sở hạ tầng endpoint routing cung cấp cách truy cập endpoint metadata trực tiếp hơn, sạch hơn thông qua HttpContext.GetEndpoint(), phù hợp với sự phát triển kiến trúc của ASP.NET Core hướng tới endpoint routing.

Hành động được khuyến nghị

Chuyển từ IActionContextAccessor sang IHttpContextAccessor và sử dụng HttpContext.GetEndpoint():

Trước:

csharp
public class MyService
{
   private readonly IActionContextAccessor _actionContextAccessor;

   public MyService(IActionContextAccessor actionContextAccessor)
   {
       _actionContextAccessor = actionContextAccessor;
   }

   public void DoSomething()
   {
       var actionContext = _actionContextAccessor.ActionContext;
       var actionDescriptor = actionContext?.ActionDescriptor;
       // Sử dụng action descriptor metadata
   }
}

Sau:

csharp
public class MyService
{
   private readonly IHttpContextAccessor _httpContextAccessor;

   public MyService(IHttpContextAccessor httpContextAccessor)
   {
       _httpContextAccessor = httpContextAccessor;
   }

   public void DoSomething()
   {
       var httpContext = _httpContextAccessor.HttpContext;
       var endpoint = httpContext?.GetEndpoint();
       var actionDescriptor = endpoint?.Metadata.GetMetadata<ActionDescriptor>();
       // Sử dụng action descriptor metadata.
   }
}

Các API bị ảnh hưởng