Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

NonActionAttribute trong ASP.NET MVC C# có ý nghĩa gì?

Attribute NonAction dùng khi muốn public method trong controller nhưng không muốn treat nó như action method. Action method là public method trong controller có thể invoke dùng URL. Mặc định, nếu có public method nào trong controller thì có thể invoke dùng URL request. Để restrict access đến public methods trong controller, NonAction attribute được dùng.

Xét HomeController có hai public methods MyMethod1 và MyMethod2.

Controller

Ví dụ

using System.Web.Mvc; 

namespace DemoMvcApplication.Controllers { 
    public class HomeController : Controller { 
        public string MyMethod1() { 
            return "<h1>My Method 1 Invoked</h1>"; 
        } 
        
        public string MyMethod2() { 
            return "<h1>My Method 2 Invoked</h1>"; 
        } 
    } 
}

Gọi cả hai methods trong HomeController dùng URLs:

https://localhost:59146/Home/MyMethod1

https://localhost:59146/Home/MyMethod2

Giả sử MyMethod2 dùng cho internal purpose, không muốn invoke qua URL. Để achieve this, decorate nó với NonAction attribute.

Controller với NonAction

Ví dụ

using System.Web.Mvc; 

namespace DemoMvcApplication.Controllers { 
    public class HomeController : Controller { 
        public string MyMethod1() { 
            return "<h1>My Method 1 Invoked</h1>"; 
        } 
        
        [NonAction] 
        public string MyMethod2() { 
            return "<h1>My Method 2 Invoked</h1>"; 
        } 
    } 
}

Output

Gọi MyMethod2 qua URL trả về 404 Not Found.

NonAction vs Private Method

Đặc điểm [NonAction] Public Method Private Method
Gọi từ action khác ✅ Có thể (this.MyMethod2()) ✅ Có thể
Gọi từ URL ❌ Không (404) ❌ Không
Unit Test ✅ Dễ dàng (public) ❌ Khó (private)
Dependency Injection ✅ Có thể inject services ✅ Có thể
Override trong derived class ✅ Có thể (virtual) ❌ Không

Use Cases phổ biến

  • Helper methods dùng chung cho multiple actions
  • Methods dùng cho AJAX calls nhưng không muốn expose trực tiếp
  • Base controller methods shared across controllers
  • Methods cần unit test độc lập

ASP.NET Core

ASP.NET Core không có NonActionAttribute. Các cách đạt hiệu quả tương tự:

// 1. Private method (khuyến nghị nhất)
private string GetFormattedName(string name) { ... }

// 2. [ApiExplorerSettings(IgnoreApi = true)] - ẩn khỏi Swagger/OpenAPI
[ApiExplorerSettings(IgnoreApi = true)]
public IActionResult InternalMethod() { ... }

// 3. [NonAction] - vẫn tồn tại trong Microsoft.AspNetCore.Mvc.Core để compatibility
[NonAction]
public IActionResult LegacyMethod() { ... }

// 4. Không public - chỉ internal/protected
internal IActionResult InternalOnly() { ... }

Lưu ý

  • NonAction không ảnh hưởng đến ActionName, Route, HttpGet/Post attributes
  • ChildActionOnly cũng ngăn truy cập URL nhưng cho phép @Html.Action()
  • Kết hợp [NonAction] + [HttpPost] vô nghĩa - NonAction ưu tiên cao hơn