How to insert central/global prefix before route path over ASP.NET Core
Sometimes we would like to add prefix before route path under different scenario. As example for distinguish WEB API from diverse environment:
https://x.x.x.x/dev_api_v1/getitems?Id=toys0803 // for development
https://x.x.x.x/qas_api_v1/getitems?Id=toys0803 // for qas
https://x.x.x.x/release_api_v1/getitems?Id=toys0803 // for release
We could simply modify each action(s) under relative controller(s).
// ⬇ we could changed route path here
// for instance: [Route("/dev_api_v1/getitems")]
[Route("getitems")]
[HttpGet]
public async Task<IActionResult> GetItems(string Id)
{
// do some logic and got result ...
// return the Json result
return Json(new { });
}
You may think that this approach was not convenient and was not easy to integrate with CI/CD process😒.
So the ideal that we would like to inject the central/global prefix before route path. Let’s do a little tricky on it.
First, declare below extension class: MvcOptionExtension.
Second, inside the class Startup.cs, insert below code snippet to enable centralize prefix binding with global route.
Then we could enjoy injection prefix route via the middle-ware and also combine into argument replacement from CI/CD among different environments😃.
The other alternative choice would be set the base path as below, so we could force our whole website with prefix path.