How can we assign alias names for the action method in C# ASP.NET WebAPI?


A public method in a controller is called an Action method. Let us consider an example where DemoController class is derived from ApiController and includes multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete.

Example

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

Based on the incoming request URL and HTTP verbv (GET/POST/PUT/PATCH/DELETE), Web API decides which Web API controller and action method to execute e.g. Get() method will handle HTTP GET request, Post() method will handle HTTP POST request, Put() mehtod will handle HTTP PUT request and Delete() method will handle HTTP DELETE request for the above Web API. So, here the Url for the Get method will be http://localhost:58174/api/demo.

An alias name for an action method is provided by using ActionName attribute. Also it is necessary to change the route template in the WebApiConfig.cs.

Example

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 Studen{
               Id = 1,
               Name = "Mark"
            },
            new Student{
               Id = 2,
               Name = "John"
            }
         };
         return Ok(students);
      }
   }
}

Now we can call the Get() method with FetchStudentsList (alias name).

Updated on: 19-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements