c# - 重用 Asp.Net Core Controller 的路由和逻辑

标签 c# asp.net rest asp.net-web-api asp.net-core

我刚刚开始使用 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 继承。

最佳答案

路由属性不能被继承。

您可以使用路由中间件。参见 documentationthe examples on Routing github repo .

我也可以推荐这个ASP.NET Core 1.0 - Routing - Under the hood文章,因为它对路由的工作原理有很好的解释:

enter image description here

关于c# - 重用 Asp.Net Core Controller 的路由和逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37943973/

相关文章:

C# ASP.NET Core Serilog 添加类名和方法来记录

c# - gridview 中的单元格值未进入 asp.net

c# - 使用 JSON.Net 进行 JObject 和 CamelCase 转换

c# - 如何使 CustomValidators 与 RequiredFieldValidators 同时触发

c# - 两个 ListItem 对象不能具有相同的 value 属性吗?

javascript - 将字符串传递给 AJAX/Json

rest - 通过 RESTful API 将新的/更新的应用程序版本部署到 Azure Batch 服务?

ruby-on-rails - 在 RESTful 响应中排除私有(private)数据

java - 在 ServiceNow 中使用 REST API 获取用户 sys_id?

c# - 将逻辑基于类型是结构的假设是一种不好的做法吗?