Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c# 4.0 - How to handle hierarchical routes in ASP.NET Web API?

Currently I have two controllers

1 - Parent Controller

2 - Child Controller

I access my Parent Controller like this

someurlparentcontroller

Now I want to access my children controller like this

someurlparentcontroller1childcontroller

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

I have this route currently in my global.asax file

routes.MapHttpRoute ("Route1", "{controller}/{id}", new { id = RouteParameter.Optional });

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

question from:https://stackoverflow.com/questions/10783946/how-to-handle-hierarchical-routes-in-asp-net-web-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 }
  );

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

The child controller:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...