如何从 Mvc 中的 HomeController 中删除 Home

How to remove Home from HomeController in Mvc

我有一个 HomeController,里面有很多 Action。我希望用户无需输入 Home 即可访问我的操作。这是下面的路线

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

我希望用户不要输入控制器名称,在本例中为 Home。我怎样才能做到这一点?还是强制性的?

您可以像这样在默认路由之前添加自定义路由:

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

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

解决方案01(属性路由)

在 RouteConfig 中其他路由的顶部添加以下行

        routes.MapMvcAttributeRoutes();

然后根据需要在每个动作的顶部添加一个属性路由。 (在这种情况下家庭控制器中的操作)
例如。下面的代码示例将从 http://site/Home/About and be available on http://site/About

中删除“/Home”
[Route("About")] 
public ActionResult About()
{

解决方案 02(使用路由约束)[Source]

添加一个新的路由映射到RouteConfig 如下。 (请记住在默认(通用)路由之前添加这些特定路由。

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

这将从 Home 控制器的所有操作(路由)中删除 "Home" RootRouteConstraint class

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

可选信息:此行(约束)将确保仅将此路由应用于 HomeController

new { isMethodInHomeController = new RootRouteConstraint<HomeController>