MVC 4 Remove “home” from base route

2020-02-16 08:38发布

问题:

Basically I want to make it so that: http://website.com/Home/About

Shows up as: http://website.com/About

The "home" controller showing up in the url would make the url longer for the user to read.

I tried to do the following:

routes.MapRoute(
            name: "About",
            url: "",
            defaults: new { controller = "Home", action = "About", id = UrlParameter.Optional }
            );

Could someone help me out please?

回答1:

Try something like this:

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "OnlyAction",
        "{action}",
        new { controller = "Home", action = "Index" } 
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );


回答2:

Try this. It also makes your URLs lowercase.

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.LowercaseUrls = true;

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

And in your Home controller:

    [Route("About")]
    public ActionResult About()
    {
        return View();
    }


回答3:

Step 1: Create the route constraint.

public class RootRouteConstraint<T> : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
            return rootMethodNames.Contains(values["action"].ToString().ToLower());
        }
    }

Step 2:
Add a new route mapping above your default mapping that uses the route constraint that we just created. The generic parameter should be the controller class you plan to use as your “Root” controller.

routes.MapRoute(
                "Root",
                "{action}",
                new {controller = "Home", action = "Index", id = UrlParameter.Optional},
                new {isMethodInHomeController = new RootRouteConstraint<HomeController>()});




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

Now you should be able to access your home controller methods like so: example.com/about, example.com/contact

This will only affects HomeController. Alll other Controllers will have the default routing functionality.