Nancy路由的定義
路由在構造函數中定義;
路由需要指定:Method(請求方式)
+ Pattern(規則)
+ Action(前處理請求的響應方法)
+ Condition(條件)
如:
public RoutesModule()
{
// Method : Get
// Pattern : "/Routes/{num:int}"
// Action : p => string.IsNullOrWhiteSpace(p.num) ? "null" : p.num
// Condition : {num:int} 約束num的類型爲int
Get("/Routes/{num:int}", p => string.IsNullOrWhiteSpace(p.num) ? "null" : p.num);
}
Method
Method是用於訪問資源的HTTP方法。 Nancy支持以下方法:DELETE,GET,HEAD,OPTIONS,POST,PUT和PATCH。
Pattern
Pattern的語法是可以自定義的。Nancy默認自帶了一下規則(
Nancy對這些默認提供的規則指定了分數,分數越高,匹配優先度越高):
1.純文字段(
Literal segments - 10000),需要完全匹配:
public RoutesModule()
{
Get("/Routes/Hello", p => "hello");
}
2.捕獲段(Capture segments - 1000),可以捕獲參數
public RoutesModule()
{
Get("/Routes/{name}", p => "hello:" + p.name);
}
也可以捕獲多個參數(Multiple Captures Segment - 100)
public RoutesModule()
{
Get("/Routes/{name}/{age}/{address}", p => "name:" + p.name + ",age:" + p.age + ",address:" + p.address);
}
或者這樣
public RoutesModule()
{
Get("/Routes/{file}.{extension}", p => "file:" + p.file + ",extension:" + p.extension);
}
3.捕獲段支持可空類型(Capture segments (optional) - 1000)
public RoutesModule()
{
Get("/Routes/{name?}", p => p.name == null ? "null" : p.name);
}
4.捕獲段支持設置默認值(Capture Segments (optional/default) - 1000)
public RoutesModule()
{
Get("/Routes/{name?default}", p => p.name == null ? "null" : p.name);
}
5.正則段(RegEx Segment - 1000),可以使用正則表達式
public RoutesModule()
{
// 匹配email
Get(@"/Routes/(?<email>^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$)", p => p.email);
}
6.貪婪段(Greedy Segment - 0),在變量末尾加*,表示匹配到最後
public RoutesModule()
{
Get(@"/Routes/{name*}", p => p.name);
}
Condition
Nancy提供了一些約束對參數類型進行限制,當類型不匹配時,請求會失敗
public RoutesModule()
{
Get("/Routes/{num:int}", p => string.IsNullOrWhiteSpace(p.num) ? "null" : p.num);
}
Nancy提供的默認約束條件有:
約束類型 | 說明 |
---|---|
int | 只允許Int32 |
long | 只允許Int64 |
decimal | 只允許decimal |
guid | 只允許Guid |
bool | 只允許true/false |
alpha | 只允許字母 |
datetime | 只允許datetime |
datetime(format) | 只允許特定格式datetime |
min(mininum) | 允許的最小整數值 |
max(maxinum) | 允許的最大整數值 |
range(mininum, maxinum) | 允許的整數值範圍 |
minlength(length) | 允許的字符串最小長度 |
maxlength(length) | 允許的字符串最大長度 |
length(length) | 允許的字符串長度範圍 |
version | 只允許版本號,例1.0.0 |
自定義約束條件
Nancy可以通過繼承 RouteSegmentConstraintBase<T> 和 ParameterizedRouteSegmentConstraintBase<T> 來自定義約束條件
- RouteSegmentConstraintBase <T> - 命名約束的基類。
- ParameterizedRouteSegmentConstraintBase <T> - 接受參數的命名約束的基類。
Example:
1.創建一個約束條件:
public class EmailRouteSegmentConstraint : RouteSegmentConstraintBase<string>
{
public override string Name
{
get { return "email"; }
}
protected override bool TryMatch(string constraint, string segment, out string matchedValue)
{
if (segment.Contains("@"))
{
matchedValue = segment;
return true;
}
matchedValue = null;
return false;
}
}
2.使用
public RoutesModule()
{
Get("/Routes/{email:email}", p => p.email);
}
3.結果
代碼下載:https://download.csdn.net/download/qq_33649351/10945491