컨트롤러 내부의 public 메서드는 액션(Action) 메서드라고 부릅니다. 예를 들어, ApiController에서 파생된 DemoController 클래스에 Get, Post, Put, Delete처럼 HTTP 동사와 이름이 일치하는 여러 액션 메서드가 포함되어 있다고 가정해 보겠습니다.
예제
public class DemoController : ApiController{
public IHttpActionResult Get(){
//Some Operation
return Ok();
}
public IHttpActionResult Post([FromUri]int id){
//Some Operation
return Ok();
}
public IHttpActionResult Put([FromUri]int id){
//Some Operation
return Ok();
}
public IHttpActionResult Delete(int id){
//Some Operation
return Ok();
}
}Web API는 들어오는 요청 URL과 HTTP 동사(GET/POST/PUT/PATCH/DELETE)를 기반으로 실행할 컨트롤러와 액션 메서드를 결정합니다. 예를 들어 위의 Web API에서는 Get() 메서드가 HTTP GET 요청을, Post() 메서드가 HTTP POST 요청을, Put() 메서드가 HTTP PUT 요청을, Delete() 메서드가 HTTP DELETE 요청을 각각 처리합니다. 따라서 Get 메서드의 요청 URL은 https://localhost:58174/api/demo가 됩니다.
액션 메서드에 별칭 이름을 지정하려면 ActionName 특성(Attribute)을 사용하면 됩니다. 이때 WebApiConfig.cs 파일에서 라우트 템플릿도 함께 변경해 주어야 정상적으로 동작합니다.
ActionName 특성 적용 예제
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class DemoController : ApiController{
[ActionName("FetchStudentsList")]
public IHttpActionResult Get(){
List<Student> students = new List<Student>{
new Student{
Id = 1,
Name = "Mark"
},
new Student{
Id = 2,
Name = "John"
}
};
return Ok(students);
}
}
}
위와 같이 설정하면 이제 Get() 메서드를 FetchStudentsList라는 별칭 이름으로 호출할 수 있습니다.
ActionName 특성을 활용하면 실제 C# 메서드 이름과 외부에 노출되는 액션 이름을 분리할 수 있습니다. 이를 통해 RESTful API 설계 시 더 유연하고 직관적인 엔드포인트를 구성할 수 있으며, 하나의 HTTP 동사에 대해 서로 다른 이름의 여러 액션 메서드를 오버로드 형태로 관리할 때도 유용하게 사용됩니다.