繁体   English   中英

REST API可选参数

[英]REST API Optional parameters

我使用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}")]

我认为使用段(即使用/)时无法实现此目的。 您可以使用通配符,但只允许在最后一段使用通配符。

[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

您可以在http://msdn.microsoft.com/zh-cn/library/bb675245.aspx中找到有关UriTemplate的更多信息。

希望这可以帮助

当定义了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)
{
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM