Reputation: 4770
I'm just getting started with Asp.Net Core (and asp.net in general) and I'm trying to build nice controller classes for my rest api.
I'm trying to inherit from a base controller to avoid redefining routes and logic such as validation for resources like so (non working example):
[Route("/api/v1/users/{id}")]
public class UserController: Controller
{
protected int userId;
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
// Validate userId..
userId = (int) RouteData.Values["id"];
}
[HttpGet]
public IActionResult Info()
{
// Use this.userId here
return this.Json("User info..");
}
}
[Route("/friends")]
public class UserFriendsController: UserController
{
[HttpGet]
public IActionResult Info()
{
// Use this.userId here
return this.Json("List of user's friends..");
}
}
I realize I can put this into a single class with multiple actions, but my real scenario involves more controllers that all may want to inherit from UserController.
Upvotes: 3
Views: 1780
Reputation: 24123
I'm trying to inherit from a base controller to avoid redefining routes and logic such as validation for resources
If you want to check whether current user has access right on the resource or not, you should use Resource Based Authorization. For other cross cutting concerns, you can use Filters or Middlewares.
Upvotes: 1
Reputation: 49789
Route attributes cannot be inherited.
You can play with Routing Middleware. See documentation and the examples on Routing github repo.
Also I can recommend this ASP.NET Core 1.0 - Routing - Under the hood article, as it has good explanation about how routing works:
Upvotes: 1