我正在尝试创建一个简单的网站。基本上它有一个Controller Home
控制器。
此控制器有一个操作Index
以string
为参数(这是一个目录)并使用该“目录”来完成其工作。
我无法弄清楚如何创建一个通用捕获所有路由,将每个URL发送到这个Action。
任何网址组合都可能存在,域名以外的任何内容都应该是字符串。
http://<domain>/2008
http://<domain>/2008/09
http://<domain>/2008/09/Fred
有谁知道怎么做?如果所有值都作为列表传递,那也没关系。
有更好的方法吗?
答案 0 :(得分:8)
试试这个:
routes.MapRoute(
"Default", "{*path}",
new { controller = "Home", action = "Index" }
);
控制器:
public class HomeController : Controller {
public ActionResult Index(string path) {
return View();
}
}
答案 1 :(得分:2)
我的第一个想法是,这是一个'坏主意'。如果您可以使用任何,他们可以向您投掷一个URL,您将不得不有一个黑名单(或白名单)。有这么多空缺。更好的方法是明确说明这些路由以及如何允许参数,然后执行处理这些接受路由的操作。然后,您将拥有一个泛型捕获所有将重定向到错误页面的路由。
感觉就像是在试图混合苹果和橘子。 ASP.NET MVC有目的地消除了“页面”的想法。除非您正在进行某种类型的文件I / O,否则没有理由为各种用户创建目录,如果是这种情况,那么它可以被抽象为比您想象的更容易在ASP.NET MVC范例中工作。
在ASP.NET MVC中,如果你想根据传递的字符串改变你正在寻找的信息(很像你传递的字符串),这是一种“安全”的方式:
routes.MapRoute(
"YearOnly",
"{year}",
new { controller = "Index", action = "ShowByYear" },
new { year = @"\d{4}" }
);
routes.MapRoute(
"YearAndMonth",
"{year}/{month}",
new { controller = "Index", action = "ShowByYearAndMonth" },
new { year = @"\d{4}", month = @"\d{2}" }
);
routes.MapRoute(
"YearMonthAndName",
"{year}/{month}/{name}",
new { controller = "Index", action = "ShowByYearMonthAndName" },
new { year = @"\d{4}", month = @"\d{2}" }
);
然后,您将使用Controller Actions中传递的路由值来确定他们如何查看数据:
ShowByYear(string year)
{
//Return appropriate View here
}
ShowByYearAndMonth(string year, string month)
{
//Return appropriate View here
}
ShowByYearMonthAndName(string year, string month, string name)
{
//Return appropriate View here
}
routes.MapRoute(
"YearOnly",
"{year}",
new { controller = "Index", action = "Show" },
new { year = @"\d{4}" }
);
routes.MapRoute(
"YearAndMonth",
"{year}/{month}",
new { controller = "Index", action = "Show" },
new { year = @"\d{4}", month = @"\d{2}" }
);
routes.MapRoute(
"YearMonthAndName",
"{year}/{month}/{name}",
new { controller = "Index", action = "Show" },
new { year = @"\d{4}", month = @"\d{2}", name = "" }
);
Show(string year)
{
//
}
Show(string year, string month)
{
//Return appropriate View here
}
Show(string year, string month, string name)
{
//Return appropriate View here
}
这种方法的优点在于MapRoute
处理URL解析;并保持riff-raff。然后,您可以设置一个只引发错误的catch-all路由。你宁愿在路由方面使用regex
进行一些解析而不是在你的控制器中(在我看来)。
这使得它保持三个重载动作,并允许更清晰和更“MVC”代码。