簡體   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