ASP Web API Routing Basics

By James Kenny
1 min read

Table of Contents

Web API has a default route of HOST/API/Controller but what if we don't want that. How do we change it? Well it's actually easy, so lets do it.

Routing in ASP Web API

Routing in Web API is very straight forward and if you have done any work in ASP MVC then it will be familiar it's just in a different place. Remember you can have WEB API and MVC co existing in the same web application. By having them in different routing tables it means you can change it as you want.

All source code is here

Routing Table

In the App_Start folder you will find WebApiConfig.cs you will find a method called register and you will see the default route

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

This is the default route, anything that comes in on API it will look for the {controller} name and pass the data there.

So lets change that, instead of using /api/ to pass it lets change it to /serversncode/ we do that by adding a new route

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

Now when we run the Web API we have two routes we can do the default /api/ or a /serversncode/

The routing here is the same as for MVC so if you have played with those routes these are the same.

Tagged in:

ASP Web API, Routing

Last Update: August 21, 2018

About the Author