使用必需的非空Guid参数路由到控制器

时间:2011-09-16 22:19:49

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

我想将http://localhost/Guid-goes-here映射到ResellerController并仅在Index 空GUID时触发该控制器的Guid-goes-here动作。

我的路由表如下所示:

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

    routes.MapRoute(
        "Reseller",
        "{id}",
        new { controller = "Reseller", action = "Index", id = Guid.Empty }  
        // We can mark parameters as UrlParameter.Optional, but how to make it required?
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

}

ResellerController上的操作如下所示:

public ActionResult Index(Guid id)
{
    // do some stuff with non-empty guid here
}

应用程序启动后,导航到http://localhost会将我引导至ResellerController,并将空Guid作为Index操作的id参数的参数。

2 个答案:

答案 0 :(得分:15)

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

    routes.MapRoute(
        "Reseller",
        "{id}",
        new { controller = "Reseller", action = "Index", id = UrlParameter.Optional },
        new { id = @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" }
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}

或者如果你想要一个比一些神秘的正则表达式更强大的约束:

public class GuidConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var value = values[parameterName] as string;
        Guid guid;
        if (!string.IsNullOrEmpty(value) && Guid.TryParse(value, out guid))
        {
            return true;
        }
        return false;
    }
}

然后:

routes.MapRoute(
    "Reseller",
    "{id}",
    new { controller = "Reseller", action = "Index", id = UrlParameter.Optional },
    new { id = new GuidConstraint() }
);

答案 1 :(得分:1)

您需要在路由定义中包含约束。看看这篇文章:http://blogs.microsoft.co.il/blogs/bursteg/archive/2009/01/11/asp-net-mvc-route-constraints.aspx