我想将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
参数的参数。
答案 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)