我刚刚开始使用 Asp.Net Core(和一般的 asp.net),我正在尝试为我的 rest api 构建漂亮的 Controller 类。
我正在尝试从基本 Controller 继承以避免重新定义路由和逻辑,例如对资源的验证(非工作示例):
[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..");
}
}
我意识到我可以将其放入具有多个操作的单个类中,但我的真实场景涉及更多 Controller ,它们都可能希望从 UserController 继承。
最佳答案
路由属性不能被继承。
您可以使用路由中间件。参见 documentation和 the examples on Routing github repo .
我也可以推荐这个ASP.NET Core 1.0 - Routing - Under the hood文章,因为它对路由的工作原理有很好的解释:
关于c# - 重用 Asp.Net Core Controller 的路由和逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37943973/