我有一个带有 Get 方法的 WebAPI Controller ,如下所示:
public class MyController : ApiController
{
public ActionResult Get(string id)
{
//do some stuff
}
}
挑战在于我正在尝试使用 Web API 实现 WebDAV。这意味着当用户向下浏览文件夹结构时,URL 将更改为如下所示:
/api/MyController/ParentFolder1/ChildFolder1/item1.txt
有没有办法将该操作路由到 MyController.Get 并提取路径,以便我得到:
ParentFolder1/ChildFolder1/item1.txt
谢谢!
最佳答案
“动态”路线不是问题。只需使用通配符:
config.Routes.MapHttpRoute(
name: "NavApi",
routeTemplate: "api/my/{*id}",
defaults: new { controller = "my" }
);
此路由应在默认路由之前添加。
问题是您想以文件扩展名结束 URL。它将被解释为对 .txt 文件的静态请求。
在 IIS7+ 中,您可以通过在 web.config 中添加行来解决这个问题:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
不要忘记,如果您使用
MyController
,那么路由段只是“我的”
关于asp.net - 使用 Web API 的动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16949459/