Versioning in Asp.Net Web API (Rest API)

As we know, Rest API can have multiple clients, and some clients may need to have some extra functionality compared with other clients for the same API methods. For this type of scenario, versioning will help us. We can apply the versioning at the API method level or controller level through attributes.

 We can have multiple API methods with the same name but with different versions, as shown below.

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

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

        /// <summary>
        /// Get all employees with sorting facility
        /// </summary>
        /// <returns></returns>
        // GET: Employees
        [Route("api/v2/employees/getemployees")]
        [HttpGet]
        //[BasicAuthentication]
        public HttpResponseMessage GetEmployees(string sortExpression = "id")
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.OK, Company.GetEmployees().SortSource(sortExpression));
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
    }
}

As shown above, we have two versions of the GetEmployees() API method. Version V1 GetEmployees() returns the response without sorting, and version V2 method returns the response with sorting by given expression. The Swagger UI displays, as shown below.

We can also apply the versioning at the controller level. For this, we need to apply the routing in WebApiConfig.Routing() method, as shown below.

using CompanyRestAPI.App_Start;
using Newtonsoft.Json.Serialization;
using System.Web.Http;

namespace CompanyRestAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi1",
                routeTemplate: "api/v1/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "DefaultApi2",
                routeTemplate: "api/v2/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            config.Filters.Add(new BasicAuthenticationAttribute());
        }
    }
}