RandomUs1r
RandomUs1r

Reputation: 4190

How to split controllers by route in Web Api 2

I have a bunch of controllers and would like to segment them via route into two groups:

            config.Routes.MapHttpRoute(
                "r1",
                "api/v1.0/route1/{controller}/{action}/{id}",
                new {id = RouteParameter.Optional}
            );

            config.Routes.MapHttpRoute(
               "r2",
               "api/v1.0/route2/{controller}/{action}/{id}",
               new { id = RouteParameter.Optional }
           );

I thought I could do this with something like:

[RoutePrefix("api/v1.0/route1")]
    public class MyController : ApiController

To make it go down ONLY route1, however I'm able to hit it via route2 also.

I also tried

[RoutePrefix("route1")]
        public class MyController : ApiController

With the same result. How can I make MyController only go down route1? Any help is greatly appreciated as always.

Upvotes: 1

Views: 233

Answers (1)

codeMonkey
codeMonkey

Reputation: 4815

You want

[RoutePrefix("api/v1.0)]
public class MyController : ApiController

and then on the method itself

[Route("route1")]
public async Task<HttpResponseMessage> RouteOne(object params)
{
 ...
}


[Route("route2")]
public async Task<HttpResponseMessage> RouteTwo(object params)
{
 ...
}

Agree with commenter who said to leave MapHttpRoute alone. Should look like this:

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

Upvotes: 1

Related Questions