重用Asp.Net核心控制器的路由和逻辑
问题描述:
我刚刚开始使用Asp.Net核心(和一般的asp.net),我正在为我的其余api构建好的控制器类。重用Asp.Net核心控制器的路由和逻辑
我试图从基站控制器继承,以避免重新定义路由和逻辑,诸如验证对于像这样的资源(非工作实施例):
[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..");
}
}
原来自己可以把这个成一个类有多个动作,但是我的真实场景涉及更多控制器,所有这些控制器都可能想要从UserController继承。
答
路由属性不能被继承。
你可以玩路由中间件。请参阅documentation和the examples on Routing github repo。
而且我可以推荐这个ASP.NET Core 1.0 - Routing - Under the hood文章,因为它在如何路由的作品很好的解释:
答
我试图从基本控制器继承,以避免重新定义 路线和逻辑如验证资源
如果您想检查当前用户是否具有辅助功能不管你的资源是否合适,你都应该使用Resource Based Authorization。对于其他横切问题,您可以使用Filters或Middlewares。