修改路由asp mvc

时间:2018-01-05 15:37:25

标签: c# asp.net asp.net-mvc asp.net-mvc-4

在我的ASP MVC应用程序中,我需要显示如下的URL路径:

  

domain.com/viewName

我有以下方式配置路线:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.RouteExistingFiles = false;
        routes.IgnoreRoute("{*allfiles}", new { allfiles = @".*\.(css|js|gif|jpg|png)" });            

        routes.MapRoute(
           "Theme",
           "theme/{theme}/{page}",
           new { controller = "Theme", action = "Index", page = UrlParameter.Optional },
           new[] { "Tenant.Controllers" }
        );

        routes.MapRoute(
           "ThemeSlider",
           "theme/slider/{id}",
           new { controller = "Theme", action = "Slider" },
           new[] { "Tenant.Controllers" }
        );

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

        routes.MapRoute(
            "Default_tenant",
            "{page}",
            new { controller = "Home", action = "Index", page = UrlParameter.Optional },
            new[] { "Tenant.Controllers" }
        );

        routes.MapMvcAttributeRoutes();
    }

但它不起作用,我必须按照以下方式指定页面参数: domain.com/?page=viewName 。如何离开以下路线的路线配置:

domain.com.co/controller/action/ domain.com.co/view

任何消化?提前致谢

1 个答案:

答案 0 :(得分:0)

你的意思是摆脱控制器?这种事情会奏效,但要注意不同控制器中路由之间的冲突:

routes.MapRoute(
    name: "HomeRoute",
    url: "{action}",
    defaults: new {controller = "Home", action = "Index"},
    constraints: new { homeControllerConstraint = new HomeControllerConstraint() }
);

现在,家庭控制器中的每个操作都映射到Domain.com/Action而不是Domain.com/Home/Action。

例如,这里有一些反映代码可以有效地确定路线是否在家庭控制器中。

internal class HomeControllerConstraint : IRouteConstraint
{
    private static readonly Lazy<HashSet<string>> homeMethods = new Lazy<HashSet<string>>(CreateHomeMethods);

    private static HashSet<string> CreateHomeMethods()
    {
        return typeof(HomeController).GetMethods().Select(e => e.Name.ToLower()).ToSet();
    }

    public static bool Exists(string name)
    {
        return homeMethods.Value.Contains(name.Trim().ToLower());
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return homeMethods.Value.Contains(values["action"].ToString().ToLower());
    }
}