Blake Blackwell
Blake Blackwell

Reputation: 7795

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!

Upvotes: 4

Views: 7428

Answers (2)

Teagan42
Teagan42

Reputation: 628

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

I was just dealing with this so try it out, and come back if you need more help.

Upvotes: 0

Nenad
Nenad

Reputation: 26617

"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"

Upvotes: 12

Related Questions