2014-10-26 66 views
1

我使用rest api構建Web角色。它的所有參數都應該是可選的默認值REST API可選參數

我嘗試這樣做:

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/param2/{param2}/param3/{param3}")] 
    public string RetrieveInformation(string param1, string param2, string param3) 
    { 

    } 

我想,這將在以下情況下工作:

https://127.0.0.1/RetrieveInformation/param1/2 

https://127.0.0.1/RetrieveInformation/param1/2/param3/3 

我怎麼能這樣做會不會?下面的工作?

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1=1}/param2/{param2=2}/param3/{param3=3}")] 
+0

請添加標籤質疑,以防止混淆... – Liran 2014-10-26 14:45:14

回答

3

我不認爲你在使用段(即使用/)時可以實現這一點。您可以使用通配符,但它只允許您爲最後一個分段執行此操作。

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/{*param2}")] 

如果你確實不需要段和可以使用的查詢參數,下面的路線將工作

[WebGet(UriTemplate = "RetrieveInformation?param1={param1}&param2={param2}&param3={param3}")] 

這樣的路線會給你的靈活性,參數並不需要訂購,也不是必要的。這將具有以下

http://localhost:62386/Service1.svc/GetData?param1=1&param2=2&param3=3 
http://localhost:62386/Service1.svc/GetData?param1=1&param3=3&param2=2 
http://localhost:62386/Service1.svc/GetData?param1=1&param2=2 
http://localhost:62386/Service1.svc/GetData?param1=1&param3=3 

您可以找到有關UriTemplate @http://msdn.microsoft.com/en-us/library/bb675245.aspx

希望更多的信息,這有助於

1

當param2的定義,所以這樣的參數1可能不是可選的工作單一路線可能有點麻煩(如果可能的話)。將你的GET分成多個路由可能會更好。根據你說的話我心底 -

如下面的代碼的東西可能會爲您提供更...

[WebGet(UriTemplate = "RetrieveInformation")] 
public string Get1() 
{ 
    return RetrieveInfo(1,2,3); 
} 

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}")] 
public string GetP1(int param1) 
{ 
    return RetrieveInfo(param1,2,3); 
} 

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/param2/{param2}")] 
public string GetP1P2(int param1, int param2) 
{ 
    return RetrieveInfo(param1,param2,3); 
} 

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/param3/{param3}")] 
public string GetP1P3(int param1, int param3) 
{ 
    return RetrieveInfo(param1,2,param3); 
} 

private string RetrieveInfo(int p1, int p2, int p3) 
{ 
    ... 
} 
+0

如果我有100個參數需要定義至少100個排列 – Yakov 2014-10-27 09:15:32

+1

如果您有100個參數,則url字符串可能不是輸入它們的最佳位置。最大URL長度是2083(或IE中路徑部分的2048)。另外,網址不會被編碼爲HTTPS,這意味着任何嗅探該線路的人都能夠在URL中查看您的所有個人信息。考慮一下帶有正文中的數據的POST會是發送此信息的更好方式。 – jt000 2014-10-27 13:22:47