Asp.net MVC / Web Api Routing: Get a little directions

I have an asp.net web api project (it works exactly the same as an Mvc project) using routing - hence I have the following

routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); 

So, everything works the way I want ... I enter api / Products / 15, it enters my product controller, passing through 15 as an identifier.

Great.

I also have 2 more controllers, 1 called UploadsController and 1 called DownloadsController. They offer downloads and downloads (GET / PUT, etc.)

Now I don’t want them to be picked up by the original rule (see above)

But I would like to use these 2 URLs to access them

/ API / Transport / Downloads / 15 / API / Transport / Downloads / 15

I went through 15 as an identifier, probably would not have happened in real life ... just its usefulness to demonstrate :-)

Now Transport does not exist, so I can do the following

 routes.MapHttpRoute( name: "API Default", routeTemplate: "api/Transports/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); 

which, I believe, works ...

but the problem is that if I do

/ api / Uploads / 15 - this will also be caught by the original rule, which I do not want.

I want the Uploads and DOwnloads controller to be accessed via fake Transports, and not without Transports

Can anyone help?

Thanks in advance

+6
source share
1 answer

You can use route restrictions and define 2 API routes in the following order:

 // matches /api/transports/downloads/id or /api/transports/uploads/id only // and no other possible controller routes.MapHttpRoute( name: "API Transport", routeTemplate: "api/transports/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { controller = "uploads|downloads" } ); // matches anything in the form /api/{controller}/id where {controller} // could be anythnig different than "downloads" or "uploads" because we don't // want to allow the following urls: /api/downloads/id and /api/uploads/id routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { controller = @"^((?!(downloads|uploads)).)*$" } ); 
+18
source

Source: https://habr.com/ru/post/918569/


All Articles