如何避免网址中的“/ Home”

时间:2015-03-29 14:21:19

标签: asp.net-mvc asp.net-mvc-routing

我在VS 2013中使用标准的MVC模板。

使用默认设置,http://website/将路由到网站/主页/索引。

如何直接在网站根网址(例如http://website/xxx)下路由所有“操作”,以显示与http://website/Home/xxx相同的内容?例如,如何让http://website/About在Home控制器中执行About操作?如果可能,解决方案不应该是Http重定向到http://website/Home/About,因为我不想在网址中显示“丑陋的”Home /。

2 个答案:

答案 0 :(得分:2)

我找不到这个问题的答案,涵盖面对公众网站所面临的所有问题,同时保持灵活性,同时保持灵活性。

我最终想出了以下内容。它允许使用多个控制器,不需要任何维护,并使所有URL小写。

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 }
        );
    }
}

答案 1 :(得分:1)

你可以试试下面的那个

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" });

在这里,您可能会注意到Home控制器是硬编码的,并且不再在请求中提供。你也可以利用RouteDebugger来玩路线。

HTH