asp.net-mvc如何省略家视图控制器名称

标签: Asp.net-MVC C#
发布时间: 2016/10/9 6:00:15
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

比方说我有这种结构︰

Home/
    Index
    About

Project/
    Index
    Details

我如何可以省略家意见的控制器名称?

我想要写 {root}/About 而不是 {root}/Home/About
我也想要 {root}/Project/Details/2 上班。

这里是我在尝试 RegisterRoutes :

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

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

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

编辑︰我也试着交换的顺序我 MapRoute 调用,但它仍然不能工作。
我需要的是︰

{root}/Home/Index         > HomeController.Index
{root}/Home               > HomeController.Index
{root}                    > HomeController.Index
{root}/Home/About         > HomeController.About
{root}/About              > HomeController.About
{root}/Project/Index      > ProjectController.Index
{root}/Project            > ProjectController.Index
{root}/Project/Details/12 > ProjectController.Details

解决方法 1:

只是更改的顺序您 MapRoute 电话︰

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

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

默认路线要最后定义,否则为它匹配所有 Url 模式,没有进一步的路线进行了评述。

更新︰

根据您的编辑,既然你想要保留 ' 控制器名称-只读工艺路线。试试这个︰

public class ActionExistsConstraint : IRouteConstraint
{
    private readonly Type _controllerType;

    public ActionExistsConstraint(Type controllerType)
    {
        this._controllerType = controllerType;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var actionName = values["action"] as string;

        if (actionName == null || _controllerType == null || _controllerType.GetMethod(actionName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase) == null)
            return false;

        return true;
    }
}

然后︰

routes.MapRoute(
    name: "HomeRoute",
    url: "{action}",
    defaults: new { controller = "Home", action = "Index" },
    constraints: new { exists = new ActionExistsConstraint(typeof(HomeController)) }
);

请参阅MSDN

官方微信
官方QQ群
31647020