ASP.NET Web API Routing

Visual Studio Scaffolder FTW 🚀

Routing is how Web API matches a URI to an action.

Right click on Controllers > Add > New Scaffolding

Write a new method in the HelloController class

public string Get()
{
return “Hello World”;
}

HTTP Verbs

HttpGet — URI Param

Go back to your HelloController, now try to add new method

[HttpGet("{name}")]
public string Get(string name)
{
return "Hello 2021! " + name;
}

HttpPost — Request Body (raw)

[HttpPost]
public string GetHelloNameBody([FromBody] string name)
{
System.Diagnostics.Debug.WriteLine("Received URI parameter : " + name);
return "Hello 2021! " + name;
}

Action Name

Now, let’s create a route where the action name is included in our URI

[HttpGet]
[ActionName("world")]
public string GetHelloWorld()
{
return "Hello World 2021!";
}

Route Attribute

[Route("/wish")]
[HttpGet]
public string GetNewYearWish()
{
return "Hello World 2021! Wish you happy!";
}