Reputation: 4727
I've to provide two Web API controllers PublicController
and PrivateController
for our system. These should have the following routes:
/public/{controller}/{id}
and
/private/{controller}/{id}
On the firewall, all requests to /private
are blocked and only available from inside the network. But by convention, both of my controllers are available for both routes, so I could request PrivateController
(which should only be available under /private
) with the url /public/PrivateController/1
.
Is there a way to specify valid controllers for a route, so that the PrivateController
is only available for the private route? Or are there some other practices to fullfill this requirement?
Thanks for your replies.
Upvotes: 1
Views: 172
Reputation: 139758
You can use the constraints
parameter to provide restrictions on the controller name in the simplest case with a very simple regular expression:
config.Routes.MapHttpRoute(
name: "private",
routeTemplate: "api/private/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { controller = @"private" }
);
config.Routes.MapHttpRoute(
name: "public",
routeTemplate: "api/public/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { controller = @"public" }
);
So the now the "private" route only accept the controller which named Private and the "public" route will only accept the controller which named Public. If you have multiple public and private controllers you can easily extend the regex to match them.
If the regex is not enough for your needs you can create your custom route contaraint with implementing the IRouteConstraint
interface. You can find an example implantation In this article.
Upvotes: 1