如何处理的ASP.NET Web API层次路线? [英] How to handle hierarchical routes in ASP.NET Web API?

查看:115
本文介绍了如何处理的ASP.NET Web API层次路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有两个控制器

1 - 父控制器

2 - 儿童控制器

2 - Child Controller

访问我的父控制器这样

someurl\parentcontroller

现在我要访问我的孩子控制器这样

Now I want to access my children controller like this

someurl\parentcontroller\1\childcontroller

这最后的网址应该返回一个特定父的所有子项。

This last url should return all the children of a particular parent.

我现在有这条路线在我的Global.asax文件

I have this route currently in my global.asax file

routes.MapHttpRoute(ROUTE1,{}控制器/(编号),新{ID = RouteParameter.Optional});

我不知道我怎么能实现我的父\\ ID \\子层次。我应该如何配置我的路线,以实现这一目标?想法?

I am not sure how can I achieve my parent\id\child hierarchy.. How should I configure my routes to achieve this? Ideas?

推荐答案

配置如下路线。该{}参数是可选的(如果你需要使用):

Configure the routes as below. The {param} is optional (use if you need):

routes.MapHttpRoute(
           name: "childapi",
           routeTemplate: "api/Parent/{id}/Child/{param}",
           defaults: new { controller = "Child", param = RouteParameter.Optional }
  );

routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         defaults: new { id = RouteParameter.Optional }
  );

然后调用子API作为/ API /父母/ 1 /子
家长可以称为简单/ API /父母/

Then call the child APi as /api/Parent/1/child The parent can be called simple as /api/Parent/

子控制器:

    public class ChildController : ApiController
    {     
        public string Get(int id)
        {
          //the id is id between parent/{id}/child  
          return "value";
        }
        .......
    }

这篇关于如何处理的ASP.NET Web API层次路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆