简体   繁体   中英

ASP.NET MVC Routes

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}", ...?!?)
            };
        }
    }
}

The one line that scared me in this post was the following

I'm trying to put my Controller in charge of mapping routes

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM