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

Cách đặt alias name cho action method trong ASP.NET MVC C#

ActionName attribute là action selector dùng cho tên khác của action method. Ta dùng ActionName attribute khi muốn action method được gọi với tên khác thay vì tên thực của method.

[ActionName("AliasName")]

Controller

Ví dụ

using System.Collections.Generic; 
using System.Web.Mvc; 

namespace DemoMvcApplication.Controllers { 
    public class HomeController : Controller { 
        [ActionName("ListCountries")] 
        public ViewResult Index() { 
            ViewData["Countries"] = new List<string> { 
                "India", "Malaysia", "Dubai", "USA", "UK" 
            }; 
            return View(); 
        } 
    } 
}

View

@{ 
    ViewBag.Title = "Countries List"; 
} 
<h2>Countries List</h2> 
<ul> 
@foreach(string country in (List<string>)ViewData["Countries"]) { 
    <li>@country</li> 
} 
</ul>

Vì đã cung cấp action name khác cho method Index, khi navigate với action name Index sẽ gặp 404 error.

Bây giờ thử navigate dùng ListCountries action name.

Các use case phổ biến

1. SEO-friendly URLs

[ActionName("san-pham-moi")]
public ActionResult NewProducts() { ... }

// URL: /Home/san-pham-moi thay vì /Home/NewProducts

2. Tránh trùng tên method

[HttpGet]
[ActionName("Edit")]
public ActionResult EditGet(int id) { ... }

[HttpPost]
[ActionName("Edit")]
public ActionResult EditPost(Product model) { ... }

3. Versioning API

[ActionName("GetUserV1")]
public ActionResult GetUser(int id) { ... }

[ActionName("GetUserV2")]
public ActionResult GetUserV2(int id) { ... }

Lưu ý quan trọng

  • ActionName chỉ thay đổi URL routing, không thay đổi tên method thực tế
  • Trong code C#, vẫn gọi method bằng tên gốc: return RedirectToAction("Index");
  • Có thể kết hợp với [HttpGet], [HttpPost], [Route]
  • ASP.NET Core khuyến khích dùng Attribute Routing [HttpGet("alias")] thay vì ActionName

ASP.NET Core - Attribute Routing (Khuyến nghị)

public class HomeController : Controller {
    [HttpGet("list-countries")]
    public IActionResult Index() { ... }
    
    [HttpGet("products/{id:int}")]
    public IActionResult GetProduct(int id) { ... }
    
    [HttpPost("products")]
    public IActionResult Create(Product product) { ... }
}