Roger
Roger

Reputation: 2326

Mapping HTTP routes in ASP.NET Web API

Let's say I have an app with orders and order details. I am trying to figure out how to best set up the architecture so I can retrieve all order details for a particular order. It would seem elegant and intuitive to have a URL structure like this:

http://example.com/api/orders/{orderid}/orderdetails

I can register a route in global.asax:

System.Web.Routing.RouteTable.Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/orders/{orderid}/orderdetails",
  defaults: new { orderid = System.Web.Http.RouteParameter.Optional }
);

But I can't figure out what method in the OrdersController class this maps to. What method signature does the above route expect in my controller class? For all I know, this isn't even valid, so feel free to recommend a different approach.

Upvotes: 1

Views: 7061

Answers (4)

Rahul Saraswat
Rahul Saraswat

Reputation: 1

Add System.Web.Http.WebHost dll reference into your web application. Thank You.

Upvotes: 0

Kumaresan Lc
Kumaresan Lc

Reputation: 281

Take a look at the following page. It will be helpful http://aspnetwebstack.codeplex.com/wikipage?title=Attribute%20routing%20in%20Web%20API

Upvotes: 0

Kniganapolke
Kniganapolke

Reputation: 5413

Take a look at amazing AttributeRouting.WebAPI package http://www.strathweb.com/2012/05/attribute-based-routing-in-asp-net-web-api/.

Upvotes: 0

Roger
Roger

Reputation: 2326

I got it working with the following.

Global.asax Application_Start:

System.Web.Routing.RouteTable.Routes.MapHttpRoute(
 name: "DefaultApi",
 routeTemplate: "api/{controller}/{orderid}/{action}"
);

Controller class:

[ActionName("OrderDetails")]
public IEnumerable<OrderDetail> GetOrderDetails(int orderId)
{
 // return data...
}

Upvotes: 3

Related Questions