3

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.

2 Answers 2

1

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:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.