REST API可选参数

时间:2014-10-26 14:23:19

标签: c# rest

我使用rest api构建Web角色。它的所有参数都应该是可选的,默认值为

我试过了:

  [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}")]

2 个答案:

答案 0 :(得分: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 :(得分:1)

当定义param2时,param1可能不是可选的,因此在单个路由中执行此操作可能有点麻烦(如果可能的话)。将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)
{
    ...
}
相关问题