2014-10-26 71 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