ASP.NET MVC 路由
我可以看一个可以编译这段代码的示例吗?
public IEnumerable<RouteBase> Routes
{
get
{
return new List<Route>()
{
new Route(...)
}
}
}
如果 RouteCollection.MapRoute()
不存在,您会怎么做?
我试图让我的控制器负责映射路由,而不是 Global.asax.cs。 public IEnumerable
是我的控制器的成员。如果控制器负责路由,那么通过在 Global.asax.cs
的 routes.MapRoute()
中使用单独的硬编码 URL 来解耦路由是一个坏主意。
回应哈维先生:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.Include(new RootController());
}
}
public static class RouteCollectionExtension
{
public static RouteCollection Include(this RouteCollection routes, IRoutedController controller)
{
foreach (var route in controller.Routes)
{
routes.Add(route);
}
return routes;
}
}
并且:
public class RootController : Controller, IRoutedController
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public IEnumerable<RouteBase> Routes
{
get
{
return new List<Route>()
{
new Route("{controller}/{action}/{id}", ...?!?)
};
}
}
}
Can I see one example that would make this piece of code compile?
public IEnumerable<RouteBase> Routes
{
get
{
return new List<Route>()
{
new Route(...)
}
}
}
What would you do if RouteCollection.MapRoute()
didn't exist?
I'm trying to put my Controller in charge of mapping routes, not Global.asax.cs. public IEnumerable<RouteBase> Routes
is a member of my Controller. If the Controller is responsible for a Route, it's a bad idea to decouple the Route by using a separate hardcoded URL in routes.MapRoute()
in Global.asax.cs
.
In response to Mr. Harvey:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.Include(new RootController());
}
}
public static class RouteCollectionExtension
{
public static RouteCollection Include(this RouteCollection routes, IRoutedController controller)
{
foreach (var route in controller.Routes)
{
routes.Add(route);
}
return routes;
}
}
And:
public class RootController : Controller, IRoutedController
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public IEnumerable<RouteBase> Routes
{
get
{
return new List<Route>()
{
new Route("{controller}/{action}/{id}", ...?!?)
};
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这篇文章中让我害怕的一行是以下内容
ASP.NET MVC 背后的整个思想是明确的关注点分离。这将破坏控制器的可测试性,因为控制器不再只是控制,而是干预路由。
The one line that scared me in this post was the following
The whole idea behind asp.net mvc is clear seperation of concerns. This will kill the testability of the controller as the controller isn't just controlling anymore but meddling with the routes.