1

This is a simple issue with managing many methods across an asp.net web api project.

We have quite a few methods like this:

ProductsApiController.GetByType(string type, string x) ProductsApiController.GetByType(string type, int limit) //method has a number of arguments.. ReportsApiController.GetAll(string x, string y) 

The problem: We have a ton of methods with custom parameters and we have to define a custom route for each of them

routes.MapRoute( name: "ProductRoute", url: "ProductsApiController/{type}/{x}" ); routes.MapRoute( name: "ReportRoute", url: "ReportsApiController/{x}/{y}" ); 

I'm simplifying the signatures, there are many methods with a lot of params and these methods don't usually have params in common.

What is the general pattern to this? Is there a better way to do this or am I only left with this.

2 Answers 2

1

I'd say for your scenario, the most logical solution would be to use attribute routing.

Yes, it would still mean you have to create a lot of routes, but since they are effectively tied to a single action, it makes most sense to have the route in an attribute decorating this action.

You can get AR from Nuget:

PM> Install-Package AttributeRouting.WebApi 

In your case it would look like this:

[GET("mytype/{type}/{x}")] public MyType GetByType(string type, string x) [GET("mytype/{type}/{limit}")] public MyType GetByType(string type, int limit) 

and so on... which, IMHO is much more manageable

A while ago I wrote an intro post to AR - http://www.strathweb.com/2012/05/attribute-based-routing-in-asp-net-web-api/

You can also visit their excellent wiki - https://github.com/mccalltd/AttributeRouting/wiki

Sign up to request clarification or add additional context in comments.

Comments

1

This is a case where passing URI parameters in the query string becomes really handy. You could define just one route and then have all the URI parameters for that action passed in through the query (e.g. ReportsApi/GetAll?x=5&y=6). You would just define a route with a path template that also includes the action ({controller}/{action}).

Otherwise, if you want all the parameters passed in within the path in different ways, I can't think of a better way. Because you have to let the routing system know where to get each parameter and what parameter name it should bind to. There isn't a convention for deciding on a parameter name the way there is for query string parameters. You could look into Filip's good suggestion of using attribute routing below. It won't reduce the number of routes you'll have to write, but at least they'll be closer to the code where you need them.

1 Comment

Yes. But adding those question marks and whatsnot make the request from javascript pretty ugly and non-restful. And then making custom routes involves managing too much code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.