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

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

问题描述

目前我有两个控制器

1 - 父控制器

2 - 子控制器

我像这样访问我的父控制器

I access my Parent Controller like this

someurlparentcontroller

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

Now I want to access my children controller like this

someurlparentcontroller1childcontroller

最后一个 url 应该返回特定父级的所有子级.

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", "{controller}/{id}", new { id = RouteParameter.Optional });

我不确定如何实现我的 parentidchild 层次结构.. 我应该如何配置我的路由来实现这一点?想法?

I am not sure how can I achieve my parentidchild hierarchy.. How should I configure my routes to achieve this? Ideas?

推荐答案

配置路由如下.{param} 是可选的(如果需要,请使用):

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/Parent/1/child父级可以简单地称为/api/Parent/

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天全站免登陆