asp.net-coreasp.net-routing

Configurable route prefix for controller


I'm using ASP.NET Core 6 and trying to have the base path of my API controller be configurable (so that users can choose the base path themselves to avoid conflicts with other controllers).

I tried setting up the following route:

string configurablePrefix = "/temp";
endpoint.MapControllerRoute(
    name: "MyRouteName",
    pattern: configurablePrefix + "/{action=MyDefaultAction},
    defaults: new { controller = "MyController" });

Where MyController is defined like this:

[ApiController]
public class MyController : ControllerBase
{
    [HttpGet("MyDefaultAction")]
    public IActionResult MyDefaultAction()
    {
        return new JsonResult("Hello");
    }
}

This causes no errors during startup, but when I access `https://localhost/temp/MyDefaultAction I get a 404

How can I get this to work so that actions in MyController are accessible on whatever start path the user chooses (i.e. change it to respond to /othertemp/MyDefaultAction instead)?


Solution

  • From your code, you are using ApiController, which cannot be routed by setting the corresponding route in Startup.cs or Program.cs.

    ApiController must have attribute routing, and attribute routing has a higher priority than conventional routing, so it will override the conventional routing you defined.

    You can choose to use attribute routing to define the controller name as temp, so that the corresponding endpoint can be matched in ApiController:

    [Route("temp")]
    [ApiController]
    public class MyController : ControllerBase
    {
        [HttpGet("MyDefaultAction")]
        public IActionResult MyDefaultAction()
        {
            return new JsonResult("Hello");
        }
    }
    

    Test Result:

    enter image description here

    Or use an MVC controller:

    public class MyController : Controller
    {
        [HttpGet]
        public IActionResult MyDefaultAction()
        {
            return new JsonResult("Hello");
        }
    }
    

    Routing:

    string configurablePrefix = "/temp";
    endpoint.MapControllerRoute(
        name: "MyRouteName",
        pattern: configurablePrefix + "/{action}",
        defaults: new { controller = "My", action = "MyDefaultAction" });
    

    Test Result:

    enter image description here

    reference link: Create web APIs with ASP.NET Core.