Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Routing with Web API

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

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

The challenge is that I am attempting to implement WebDAV using Web API. What this means is that as a user browses down a folder structure the URL will change to something like:

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

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

ParentFolder1/ChildFolder1/item1.txt

Thanks!

like image 330
Blake Blackwell Avatar asked Dec 11 '22 14:12

Blake Blackwell


1 Answers

"Dynamic" route is not a problem. Simply use wildcard:

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

This route should be added before default one.

Problem is that you want to end URL with file extension. It will be interpreted as static request to .txt file. In IIS7+ you can work around that by adding line in web.config:

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

Don't forget that if you use MyController, then route segment is just "my"

like image 96
Nenad Avatar answered Dec 27 '22 08:12

Nenad