tom
tom

Reputation: 1822

Web Api route filter to sub directory

Inside my Controllers directory I have two sub directories - FeaturesA and FeaturesB

FeaturesA
      Service1Controller 
      Service2Controller 
      Service3Controller

FeaturesB 
      Service4Controller
      Service5Controller
      Service6Controller

I want to add two routes so that I can access these services via the following URLs -

localhost/api/FeaturesA/....

and

localhost/api/FeaturesB/....

I have the follwing route setup

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

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

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

BUT I can access Service1 from localhost/api/FeaturesA/Service1 and localhost/api/FeaturesB/Service1 and even localhost/api/Service1

How do I setup my routes to only allow Service1 to accessed from localhost/api/FeaturesA/Service1, same applies to all the other controllers, i.e. they should only be accessible from a url which matches their controller sub dir.

Upvotes: 2

Views: 2796

Answers (1)

Sixten Otto
Sixten Otto

Reputation: 14816

This seems like pretty much exactly what routing constraints were introduced to accomplish. If you have a simple enough case, you could use the built-in types to just add regular expressions to match against the controller names. But for more complex cases, you could write your own.

Pinal Bhatt has a nice blog post with links to a bunch of articles on the subject here: http://blog.pbdesk.com/2012/07/route-constraints-with-aspnet-mvc.html

Upvotes: 3

Related Questions