使用必需的非空Guid参数路由到控制器 [英] Routing to controller with a required, non-empty Guid parameter
本文介绍了使用必需的非空Guid参数路由到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将 http://localhost/Guid-goes-here 映射到Guid-goes-here
不是空的Guid时才触发该控制器的Index
动作.
I would like to map http://localhost/Guid-goes-here to ResellerController
and fire Index
action of that controller only when Guid-goes-here
is not the empty 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
);
}
ResellerController
上的操作如下:
public ActionResult Index(Guid id)
{
// do some stuff with non-empty guid here
}
应用程序启动后,导航至 http://localhost 会将我引导至ResellerController
,其中Guid为空Index
操作的id
参数的参数.
Once the application has started, navigating to http://localhost routes me to the ResellerController
with the empty Guid as the argument to the Index
action's id
parameter.
推荐答案
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
);
}
或者如果您想要比某些隐秘正则表达式更强大的约束:
or if you want a more robust constraint than some cryptic regex:
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() }
);
这篇关于使用必需的非空Guid参数路由到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文