Dynamic Routing with Web API

2019-04-09 23:23发布

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!

2条回答
唯我独甜
2楼-- · 2019-04-09 23:37

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

查看更多
The star\"
3楼-- · 2019-04-09 23:56

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.

查看更多
登录 后发表回答