A-A+

Defining routes 定义路由(下) (Nancy 官方文档翻译)

2016年01月27日 站长资讯 暂无评论

路由片段约束

路由片段约束允许你给路由片段使用一个特定的约束。应用约束到片段仅需要在要约束的名称后添加一个:。

Get["/intConstraint/{value:int}"] = parameters => "Value " + parameters.value + " is an integer.";

上面的结果是路由的value片段只接受整形数据。

下面是预定义好的约束:

  1. int - Allows only Int32 (int) values.  
  2. long - Allows only Int64 (long) values.  
  3. decimal - Allows only decimal values.  
  4. guid - Allows only GUID values.  
  5. bool - Allows only boolean values.  
  6. alpha - Allows only values containing alphabetical character.  
  7. datetime - Allows only date values, optionally containing time.  
  8. datetime(format) (Added in 0.22) - Allows only date and/or time values with the specified format. For format values, seeCustom Date and Time Format Strings  
  9. min(minimum) - Allows only integer values with the specified minimum value.  
  10. max(maximum) - Allows only integer values with the specified maximum value.  
  11. range(minimum, maximum) - Allows only integer values within the specified range. (Between minimum and maximum)  
  12. minlength(length) - Allows only values longer than the specified minimum length.  
  13. maxlength(length) - Allows only values shorter that the maximum length.  
  14. length(minimum, maximum) - Allows only values with length within the specified range. (Between minimum and maximum)  
  15. version (Added in 1.2) - Allows only Version values, e.g. 1.2.0.  

自定义约束

你也可以实现自己的自定义约束。很容易通过实现 IRouteSegmentConstraint, Nancy可以自动识别自定义约束, SDHP-style。 你也可以继承下面的工具类实现:

RouteSegmentConstraintBase - Base class for a named constraint.

ParameterizedRouteSegmentConstraintBase - Base class for a named constraint that accepts arguments.

例子:邮件约束的实现示例 (although very simplified):

  1. public class EmailRouteSegmentConstraint : RouteSegmentConstraintBase<string>  
  2. {    public override string Name  
  3.     {        get { return "email"; }  
  4.     }      
  5.     protected override bool TryMatch(string constraint, string segment, out string matchedValue)  
  6.     {        if (segment.Contains("@"))  
  7.         {  
  8.             matchedValue = segment;            return true;  
  9.         }  
  10.    
  11.         matchedValue = null;        return false;  
  12.     }  
  13. }  

And usage:

Get["/profile/{value:email}"] = parameters => "Value " + parameters.value + " is an e-mail address.";

This route will only get hit as long as the value segment contains a @. The value that's passed to the route is the value returned through the matchedValue out parameter.

资源:

Head over to the Constraints Sample Project to look at some samples or take a look at the existing constraint implementations.

选择调用正确路由的秘籍

There are a couple of gotchas you should be aware of when it comes to the default behavior, in Nancy, for selecting which route to invoke for a request. It sounds easy enough, you pick the one that matches the Method, Pattern and Condition of the request, right? In the simplest case that is true and how it is selected, but what if things are a bit more complicated?
You could, for example, have two routes with patterns that would capture the same request under certain circumstances. These two routes could either be defined in the same module or split across several modules.

Turns out it’s not complicated after all, you just need to remember a couple of things
The order in which modules are loaded are non-deterministic in between application start-ups
Routes in a given module are discovered in the order in which they are defined
If there are several possible matches, the most specific match, i.e the route pattern that has the highest number of matching literal segments and fewest capture segments
If two, or more, routes are equal matches to a request, the first one is selected and which one this is depends on the module load order and the route order inside of the modules

疯狂的路由

  1. Below are some samples of what routes in Nancy can look like. They cover some of the possible usages, but not all of them.  
  2. // would capture routes like /hello/nancy sent as a GET request  
  3. Get["/hello/{name}"] = parameters => {      
  4.     return "Hello " + parameters.name;  
  5. };  
  6.    
  7. // would capture routes like /favoriteNumber/1234, but not /favoriteNumber/asdf as a GET request  
  8. Get["/favoriteNumber/{value:int}"] = parameters => {  
  9.     return "So your favorite number is " + parameters.value + "?";  
  10. };  
  11.    
  12. // would capture routes like /products/1034 sent as a DELETE request  
  13. Delete[@"/products/(?<id>[\d]{1,7})"] = parameters => {  
  14.     return 200;  
  15. };  
  16.    
  17. // would capture routes like /users/192/add/moderator sent as a POST request  
  18. Post["/users/{id}/add/{category}"] = parameters => {  
  19.     return HttpStatusCode.OK;  
  20. };  
标签:

给我留言