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

Dar*_*usz 8 asp.net-mvc asp.net-mvc-routing

我要地图的http://本地主机/ GUID的推移,这里ResellerController和火Index,只有当该控制器的作用Guid-goes-here不是空的Guid.

我的路由表如下所示:

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

}
Run Code Online (Sandbox Code Playgroud)

ResellerController看起来像这样的动作:

public ActionResult Index(Guid id)
{
    // do some stuff with non-empty guid here
}
Run Code Online (Sandbox Code Playgroud)

应用程序启动后,导航到http:// localhost将我路由到ResellerController空Guid作为Indexaction id参数的参数.

Dar*_*rov 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
    );
}
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

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