How to avoid “/Home” in the url

前提是你 提交于 2019-12-13 18:28:45

问题


I am using the standard MVC template in VS 2013.

With the default set up, http://website/ will be routed to website/Home/Index.

How do I route all "actions" directly under website root url, eg http://website/xxx, to show the same content as http://website/Home/xxx? For example, how do I make http://website/About to execute the About action in the Home controller? If possible, the solution shouldn't be a Http redirect to http://website/Home/About because I don't want to show the "ugly" Home/ in the url.


回答1:


you can try out like the following one

routes.MapRoute(
                name: "MyAppHome",
                url: "{action}/{wa}",
                defaults: new { controller = "Home", action = "Index", wa = UrlParameter.Optional, area = "Admin" },
                namespaces: new string[] { "MyApp.Controllers" }
            ).DataTokens = new RouteValueDictionary(new { area = "Admin" });

Here, you may notice that the Home controller is hardcoded and is no longer to be supplied in the request. you can also make use of the RouteDebugger to play with routes.

HTH




回答2:


I couldn't find an answer to this that covered all issues one would face with a public facing website without being a pain to upkeep while still maintaining flexibility.

I ended up coming up with the following. It allows for use of multiple controllers, doesn't require any upkeep, and makes all URLs lowercase.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        //set up constraints automatically using reflection - shouldn't be an issue as it only runs on appstart
        var homeConstraints = @"^(?:" + string.Join("|", (typeof(Controllers.HomeController)).GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly).Select(x => (x.Name == "Index" ? "" : x.Name))) + @")$";

        //makes all urls lowercase, which is preferable for a public facing website
        routes.LowercaseUrls = true;

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

        //maps routes with a single action to only those methods specified within the home controller thanks to contraints
        routes.MapRoute(
            "HomeController",
            "{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new { action = homeConstraints }
        );

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


来源:https://stackoverflow.com/questions/29330258/how-to-avoid-home-in-the-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!