如何创建 System.Guid 类型的路由约束?
谁能告诉我如何绘制需要两个向导的路线的正确方向?
IE。 http://blah.com/somecontroller/someaction/{firstGuid}/{secondGuid}
其中都是firstGuid和 secondaryGuid 不是可选的,并且必须是 system.Guid 类型?
Can anyone point me in the right direction on how to map a route which requires two guids?
ie. http://blah.com/somecontroller/someaction/{firstGuid}/{secondGuid}
where both firstGuid and secondGuid are not optional and must be of type system.Guid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
创建一个 RouteConstraint 如下所示:
接下来添加路由时:
Create a RouteConstraint like the following:
Next when adding the route :
对于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)。
For MVC 5 there is already implemented the GuidRouteConstraint Class:
https://msdn.microsoft.com/en-us/library/system.web.mvc.routing.constraints.guidrouteconstraint(v=vs.118).aspx
Full list of available MVC constraints:
https://msdn.microsoft.com/en-us/library/system.web.mvc.routing.constraints(v=vs.118).
如果您使用 kazimanzurrashid 的代码,请确保包含 Nikos D 的注释。我最终得到了这个:
If you use kazimanzurrashid's code, make sure to include Nikos D's comment. I ended up with this:
绝对要警惕@kazimanzurrashid 给出的代码。这是一个好的开始,但它肯定也有一个错误。我将一个真正的 Guid 传递到路线值中(而不是 Guid 字符串),但我无法获得任何与我的路线相匹配的内容。我花了很长时间才意识到 GuidConstraint 是对真正的 Guid 的约束,如果这有意义的话。 :)
这就是我最终得到的结果,它接受任何数据类型(不仅仅是字符串),速度更快一些(我认为),并且包含更少的 if 块 嵌套。
Definitely be wary of the code given by @kazimanzurrashid. It was a good start, but it definitely has a bug or too. I was passing a real Guid into the route values (instead of a string of a Guid), and I couldn't get anything to match my route. It took me forever to realize that the GuidConstraint was constraining against a real Guid, if that makes any sense. :)
Here's what I ended up with, which accepts any data type (not just string), is a bit faster (I think), and contains less if block nesting.
+1 @kazimanzurrashid。看起来很准。
我将为那些没有 C#4.0 的人提供一个替代方案,其中 Guid.TryParse 是其中的一部分。正则表达式还有另一种选择,但可能不值得打扰了。
+1 @kazimanzurrashid. Seems spot on.
I'll give an alternative for those who haven't got C#4.0, of which Guid.TryParse is part of. There's another alternative with Regex but probably not worth the bother.
我发现,在使用 @Html.RouteLink(...) 之类的东西以及在以字符串形式提供 URL 的路由测试中,假设类型是 Guid 会导致问题。下面的代码适合这些情况。使用上面的代码示例在我的视图和/或测试中引起了问题,下面的代码工作正常。
I found that assuming the type is a Guid causes issue when using things like @Html.RouteLink(...) and in Routing tests where the URL is supplied as a string. The code below caters for these situations. Using the above code samples caused issues in my views and/or tests, this below works fine.