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)?
From your code, you are using
ApiController, which cannot be routed by setting the corresponding route inStartup.csorProgram.cs.ApiControllermust 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 inApiController:Test Result:
Or use an MVC controller:
Routing:
Test Result:
reference link: Create web APIs with ASP.NET Core.