我的第一个想法是这是一个“坏主意”。如果您可以获取他们可以向您扔的任何东西,那么您将不得不拥有一个黑名单(或白名单)。有这么多的开口。更好的方法是明确说明这些路由以及您如何允许参数,然后执行处理这些已接受路由的操作。然后,您将拥有一个通用捕获所有路由,该路由将重定向到错误页面。
感觉就像你在尝试混合苹果和橙子。 ASP.NET MVC 故意取消了“页面”的想法。除非您正在执行某种文件 I/O,否则实际上没有理由为各种用户提供目录,如果是这种情况,那么可以将其抽象为在 ASP.NET MVC 范例中工作比您想象的要容易得多。
在 ASP.NET MVC 中,如果你想根据传递的字符串(很像你传递的字符串)改变你正在寻找的信息,这里有一个“安全”的方法:
方法 #1 - 三个路线、三个动作、不同的名称
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}" }
);
然后您将使用控制器操作中传递的路由值来确定它们如何查看数据:
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
}
方法 #2 - 建议方法
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 解析;并阻止即兴演奏。然后,您可以设置一个只会引发错误的包罗万象的路线。你宁愿在路由端使用regex 完成一些解析,而不是在你的控制器中(在我看来)。
这使它减少到三个重载的操作,并允许更清洁和更“MVC”的代码。