ASP.NET MVC:具有 id 约束的默认路由

ASP.NET MVC: Default route with id constraint

当我尝试如下向默认路由添加约束时

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

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

和运行网站,我得到:

HTTP Error 403.14 - Forbidden error

The Web server is configured to not list the contents of this directory.

只是这一行有约束导致了这个问题。当它被评论时,该网站如预期的那样 运行 。我什至可以在新创建的 MVC 项目上在本地复制它。

这是某种错误,还是我不了解有关路由约束的重要内容?

我正在使用 .NET 4.5.2、MVC 5.2.3、VS 2015 和 IIS Express 10.0。

没试过,你可能想定义两条路由来实现你需要的

 routes.MapRoute(
                name: "Default1",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index"}, 
                constraints: new {id=@"\d+"}
            );

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

如果 id 为空,它会回退到默认路由。

好的,我想你的问题和解决方案可以find here

适合您情况的解决方案:

public class NullableConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (routeDirection == RouteDirection.IncomingRequest && parameterName == "id")
        {
            // If the userId param is empty (weird way of checking, I know)
            if (values["id"] == UrlParameter.Optional)
                return true;

            // If the userId param is an int
            int id;
            if (Int32.TryParse(values["id"].ToString(), out id))
                return true;
        }

        return false;
    }
}

你的路线:

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