2016-06-10 111 views
0

我有這樣的路線:網頁API路由約束元組

config.Routes.MapHttpRoute(
    name: "DefaultApi", 
    routeTemplate: "api/{tenantParam1}/{tenantParam2}/{controller}/{id}, 
    constraints: ???, 
    defaults: new { id = RouteParameter.Optional } 
); 

對於tenantParam1和tenantParam2,我需要這樣只有值的某些元組被允許約束它們。有沒有辦法做到這一點?

編輯:爲了澄清,重要的是我需要將tenantParam1和tenantParam2作爲一個元組來評估。舉例來說,可以說這是我的合法租戶:

param1 | param2 
ABC | 123 
ABC | 456 
DEF | 789 
DEF | 012 

這將意味着以下途徑是有效的:

/api/ABC/123 
/api/ABC/456 
/api/DEF/789 
/api/DEF/012 

但以下途徑都無效:

/api/ABC/789 
/api/ABC/012 
/api/DEF/123 
/api/DEF/456 
+1

鏈路只回答不喜歡,但我不會粘貼整個後在這裏,所以只需閱讀:https://chsakell.com/2013/10/13/web-api-custom-routing-constraints/ –

+0

謝謝,但這似乎只包含單個參數的自定義約束。我需要將兩個參數一起約束爲一個元組。 – ConditionRacer

回答

1

這只是一個例子,你必須根據你的需要來調整它。創建約束類

public class SomeConstraint : IHttpRouteConstraint 
{ 
    public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, 
     IDictionary<string, object> values, HttpRouteDirection routeDirection) 
    { 
     //get value from values dictionary object 
     //return true or false 
     //false will block the call 
    } 
} 

然後將其註冊在配置文件中

public static void Register(HttpConfiguration config) 
    { 
     var constraintResolver = new DefaultInlineConstraintResolver(); 
     constraintResolver.ConstraintMap.Add("someConstraint", typeof(SomeConstraint)); 

     config.MapHttpAttributeRoutes(constraintResolver); 
    } 

,並用它如下

[Route("{value:someConstraint}")] 
+0

這隻允許我一次約束一個參數。我需要一個約束條件,允許我將tenantParam1和tenantParam2一起評估 – ConditionRacer

+0

看起來像這樣仍然可以使用,因爲所有路由值都傳遞給Match匹配方法。它只需要這樣註冊:'constraints:new {tenantParam1 = new TenantConstraint()}' – ConditionRacer

+1

你可以傳入多個參數,這一切都取決於你如何設置和裝飾你的路線 –