Dynamic Routing Using the Web API

I have a WebAPI controller with the Get method as follows:

public class MyController : ApiController { public ActionResult Get(string id) { //do some stuff } } 

The problem is that I am trying to implement WebDAV using the Web API. This means that as the user browses through the folder structure, the URL will change to something like:

/api/MyController/ParentFolder1/ChildFolder1/item1.txt

Is there a way to redirect this action to MyController.Get and extract the path so that I get:

 ParentFolder1/ChildFolder1/item1.txt 

Thanks!

+4
source share
2 answers

A โ€œdynamicโ€ route is not a problem. Just use a wildcard:

 config.Routes.MapHttpRoute( name: "NavApi", routeTemplate: "api/my/{*id}", defaults: new { controller = "my" } ); 

This route must be added to the default value.

The problem is that you want to complete the URL with a file extension. It will be interpreted as a static request in a .txt file. In IIS7 +, you can get around this by adding a line to web.config:

 <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> 

Do not forget that if you use MyController , then the route segment is simply โ€œmineโ€

+13
source

Use the NuGet "AttributeRouting Web API" package. You can specify specific routes for each action, including dynamic parameters.

I just dealt with this, so try and come back if you need more help.

0
source

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


All Articles