我希望从/ files / {action}和/ api / files / {action}都可以访问我的FilesController。我尝试过
routes.MapRoute(
name: "Files",
url: "api/Files/{action}/{id}",
defaults: new { controller = "Files", id = UrlParameter.Optional }
);
但是它不起作用。我删除了WebApiConfig,因此在App_Start中只有MVC RouteConfig,但这没有帮助。
更新
控制器代码
public class FilesController : Controller {
public ActionResult Index() {
return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
}
}
请求网址:
/ files / index->确定(200)
/ api / files / index->找不到(404)
更新#2
完成RouteConfig.cs
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "FilesRoute",
url: "Files/{action}/{id}",
defaults: new { controller = "Files", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Files",
url: "api/Files/{action}/{id}",
defaults: new { controller = "Files", id = UrlParameter.Optional }
);
}
}
答案 0 :(得分:1)
我认为您可以尝试在原始路线设置之前添加新路线。
此设置将首先检查URL是否与Files/{action}/{id}
匹配,如果不匹配则使用api/Files/{action}/{id}
routes.MapRoute(
name: "FilesRoute",
url: "Files/{action}/{id}",
defaults: new { controller = "Files", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Files",
url: "api/Files/{action}/{id}",
defaults: new { controller = "Files", id = UrlParameter.Optional }
);
编辑
问题是路由设置顺序,您需要将默认路由设置为最后一条。
/api/files/index
=>否则,该设置将找到api
控制器和files
动作。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "FilesRoute",
url: "Home/{action}/{id}",
defaults: new { controller = "Home", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Files",
url: "api/Home/{action}/{id}",
defaults: new { controller = "Home", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}