Asp.Net Web API – How to Change URI for Specific Action Method

In Asp.Net Web API, by default, URI is in api/{controller}/{action method} format. But sometimes, we may have a requirement to change the URI. In this article, we discuss how to change the default URI for a specific action method.

using CompanyRestAPI.Models;
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http; 

namespace CompanyRestAPI.Controllers
{
    public class EmployeesController : ApiController
    {
        // GET: Employees
        [Route("api/employees/getemployees")]
        [HttpGet]
        public HttpResponseMessage GetEmployees()
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.OK, Company.GetEmployees());
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
    }
}

The above code URL will be https://localhost:44358/api/employees/getemployees. For example, if you want to remove the api from URI, that means you want the URL as https://localhost:44358/employees/getemployees, then change the Route attribute value, as shown below.

namespace CompanyRestAPI.Controllers
{
    public class EmployeesController : ApiController
    {
        // GET: Employees
        [Route("employees/getemployees")]
        [HttpGet]
        public HttpResponseMessage GetEmployees()
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.OK, Company.GetEmployees());
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }      
    }
}

The above code works for https://localhost:44358/employees/getemployees URL. In this way, by changing the Route attribute value, we can change the specific action method URL.

If you want to change the URL for all action methods within the project, update the WebApiConfig.cs class Register() method.