Home > Software engineering >  Global route for all ApiControllers in .Net 6
Global route for all ApiControllers in .Net 6

Time:05-14

In all of my projects i put this code in top my controllers :

[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IActionResult GetTest1()
    {
        return Ok();
    }
    [HttpGet]
    public IActionResult GetTest2()
    {
        return Ok();
    }
    [HttpPost]
    public IActionResult PostTest1(string Request)
    {
        return Ok("value was "   Request);
    }
}

So i can call my APIs with action name without specify each action route, Like below picture from my swagger :

enter image description here

This work fine but i need to put this route top of all my ApiControllers in my project, I look for global solution, for Example something like this in my program.cs file :

app.MapControllerRoute(
    name: "default",
    pattern: "api/{controller}/{action}");

Problem is i can't make this code work when i delete RouteAttribute from my APIs.

CodePudding user response:

Just followed this simple tutorial on enter image description here

my progam.cs

 builder.Services.AddMvc(opt =>
 {
     opt.UseCentralRoutePrefix(new RouteAttribute("core/v1/[controller]/[action]"));
 }

).AddControllersAsServices().AddNewtonsoftJson();

CodePudding user response:

I search few hours for this and after all i didn't find any simple solution for creating good, simple, fast global route for APIs, Then i tried on my own.

You can create a base class for your APIs and put your route in that file, Then you only inherit from that class in all of your APIs.

APIBase.cs file :

[ApiController]
[Route("api/[controller]/[action]")]
public class APIBase: ControllerBase
{
}

Next step : If you need have id (or any other parameter) in your URL so you should add RouteAttribute only for that method.

ValuesController.cs file :

public class ValuesController : APIBase
{
    [HttpGet]
    public IActionResult GetTest1()
    {
        return Ok();
    }
    [HttpGet]
    [Route("{id?}")]
    public IActionResult GetTest2(int id)
    {
        return Ok("value was "   id);
    }
    [HttpPost]
    public IActionResult PostTest1(string Request)
    {
        return Ok("value was "   Request);
    }
}

And your swagger will be like this :

enter image description here

  • Related