【问题标题】:MVC Route with condition checking带有条件检查的 MVC 路由
【发布时间】:2014-03-05 14:43:36
【问题描述】:

我的 MVC4 中有以下路线...

routes.MapRoute("Account", "Account/{action}", new { controller = "Account", action = "Index" });
routes.MapRoute("Admin", "Admin/{action}", new { controller = "Admin", action = "Index" });            
routes.MapRoute("Custom", "{action}", new { controller = "Home", action = "Index" });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });

...并且需要找到一种方法将所有在 url 中具有 2 符号(www.domain.com/word2pdf)的 url 路由到操作索引并将 url 路径(word2pdf)作为api 参数传递。

public ActionResult Index(string api)
{ 
}

有什么想法吗?

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-4 c#-4.0 asp.net-mvc-routing


【解决方案1】:

正如@Murali 所说,正确的方法是使用属性路由,但这只是 mvc5 的新功能。

如果您想或必须留在 mvc4:

routes.MapRoute(name: "SomeRoutingName",
  url: "{api}",
  defaults: new { controller = "SomeControllerName", action = "Index"},
  constraints: new { api= ".+2.+"});

也只是为了一些大声笑,这也应该有效:

routes.MapRoute(name: "SomeRoutingName",
  url: "{partA}2{partB}",
  defaults: new { controller = "SomeControllerName", action = "Index" });

在控制器中:

public ActionResult Index(string partA, string partB)
{ 
     var api = string.Concat(partA,"2",partB);
}

【讨论】:

  • 优秀的答案,两个建议都按预期工作!
猜你喜欢
  • 2013-05-07
  • 1970-01-01
  • 2012-04-01
  • 2019-05-10
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
相关资源
最近更新 更多