dev*_*ife 39 asp.net-mvc asp.net-mvc-routing
任何人都可以指出我正确的方向如何绘制一个需要两个guid的路线?
即.http://blah.com/somecontroller/someaction/ {firstGuid}/{secondGuid}
其中firstGuid和secondGuid都不是可选的,必须是system.Guid类型?
kaz*_*hid 48
创建一个RouteConstraint,如下所示:
public class GuidConstraint : IRouteConstraint {
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (values.ContainsKey(parameterName))
{
string stringValue = values[parameterName] as string;
if (!string.IsNullOrEmpty(stringValue))
{
Guid guidValue;
return Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty);
}
}
return false;
}}
Run Code Online (Sandbox Code Playgroud)
接下来添加路线时:
routes.MapRoute("doubleGuid", "{controller}/{action}/{guid1}/{guid2}", new { controller = "YourController", action = "YourAction" }, new { guid1 = new GuidConstraint(), guid2 = new GuidConstraint() });
Run Code Online (Sandbox Code Playgroud)
Kry*_*zal 19
对于MVC 5,已经实现了GuidRouteConstraint类:https://msdn.microsoft.com/en-us/library/system.web.mvc.routing.constraints.guidrouteconstraint(v = vs.118).aspx
可用的MVC约束的完整列表:
https://msdn.microsoft.com/en-us/library/system.web.mvc.routing.constraints(v=vs.118).
dan*_*wig 10
如果您使用kazimanzurrashid的代码,请务必包含Nikos D的评论.我最终得到了这个:
public class NonEmptyGuidRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (values.ContainsKey(parameterName))
{
var guid = values[parameterName] as Guid?;
if (!guid.HasValue)
{
var stringValue = values[parameterName] as string;
if (!string.IsNullOrWhiteSpace(stringValue))
{
Guid parsedGuid;
Guid.TryParse(stringValue, out parsedGuid);
guid = parsedGuid;
}
}
return (guid.HasValue && guid.Value != Guid.Empty);
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
绝对要小心@kazimanzurrashid给出的代码.这是一个好的开始,但它肯定有一个bug或者也是.我正在将一个真正的Guid传递给路线值(而不是一个Guid的字符串),我无法得到任何与我的路线匹配的东西.我永远意识到GuidConstraint正在限制一个真正的Guid,如果这有任何意义的话.:)
这是我最终得到的,它接受任何数据类型(不仅仅是字符串),更快(我认为),并且包含更少的块嵌套.
public class GuidConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
object value;
if (!values.TryGetValue(parameterName, out value)) return false;
if (value is Guid) return true;
var stringValue = Convert.ToString(value);
if (string.IsNullOrWhiteSpace(stringValue)) return false;
Guid guidValue;
if (!Guid.TryParse(stringValue, out guidValue)) return false;
if (guidValue == Guid.Empty) return false;
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9598 次 |
最近记录: |