Reputation: 2447
I have a base controller where most of my api logic sits. I want to standardise the api verbs and I want this base controller to handle most request by default unless I inherit from this controller and override the specific action.
Given a path like this: "/api/Socks/Get?apiKey=1" I am able to do something like this:
[Route("api/[controller]/[action]")]
public class RestDbApiController : Controller
{
[HttpGet]
public virtual async Task<JsonResult> Get(string apiKey = null) {
.....
public class SockController : RestDbApiController
{}
This works okay - ie. the request is routed the action on the base controller. The issue is that I have to declare the SockController, otherwise the request will not route.
I would like to be able to route all requests to "/api/xxxxx" to the base controller without having to declare any other controllers. Please let me know if there is any way to do this.
Why do I want to do this? I'm trying to make a generic controller with external scripted definitions. Depending on the controller name it would read the script from a similarly named script file. I want to be able to just add the script file to a directory and have it work just like that without having to make any declarations in the code
Upvotes: 2
Views: 3172
Reputation: 49769
I agree with @Chris, but if you want to have only one controller, you could omit the "controller name" part from the routing definition. For example, the following requests will be mapped to below action method
/api/Socks/Get?apiKey=1
/api/OtherSocks/Get?apiKey=1
and name
parameter will be filled as "Socks", "OtherSocks" respectively:
public class RestDbApiController : Controller
{
[HttpGet]
[Route("api/{name}/[action]")]
public virtual async Task<JsonResult> Get(string name, string apiKey = null)
{
...
}
}
Upvotes: 2
Reputation: 239210
This isn't really practically possible. You can technically just bind a wildcard route to the controller, but that will then swallow everything. In other words, all your API routes would hit this base controller forever, and you then have to basically set up your own routing infrastructure inside that base controller to reroute requests to the right controller. In case it's not obvious, that's an extremely bad idea.
The best thing to do is actually the thing you don't want to do: actually define the derived controller. While you may look at this like it's extraneous, it's actually not at all. It serves to make your code self-documenting. It's clear that this is a controller that deals with "socks", but it doesn't have any specific logic of it's own. That's perfectly okay.
Upvotes: 4