[英]Optional UriTemplate parameter using WebGet
我試過這些
WCF服務URI模板中的可選參數? Kamal Rawat在博客中發表| 2012年9月4日的.NET 4.5本節介紹如何在WCF Servuce URI inShare中傳遞可選參數
和
但沒有什么對我有用。 這是我的代碼:
[WebGet(UriTemplate = "RetrieveUserInformation/{hash}/{app}")]
public string RetrieveUserInformation(string hash, string app)
{
}
如果填充參數,它可以工作:
https://127.0.0.1/Case/Rest/Qr/RetrieveUserInformation/djJUd9879Hf8df/Apple
但如果app
沒有價值,則無效
https://127.0.0.1/Case/Rest/Qr/RetrieveUserInformation/djJUd9879Hf8df
我想讓app
可選。 怎么做到這一點?
當app
沒有值時,這是錯誤:
Endpoint not found. Please see the service help page for constructing valid requests to the service.
此方案有兩種選擇。 您可以在{app}
參數中使用通配符( *
),這意味着“URI的其余部分”; 或者您可以為{app}
部分提供一個默認值,如果它不存在,將使用該部分。
您可以在http://msdn.microsoft.com/en-us/library/bb675245.aspx上查看有關URI模板的更多信息,下面的代碼顯示了兩種替代方案。
public class StackOverflow_15289120
{
[ServiceContract]
public class Service
{
[WebGet(UriTemplate = "RetrieveUserInformation/{hash}/{*app}")]
public string RetrieveUserInformation(string hash, string app)
{
return hash + " - " + app;
}
[WebGet(UriTemplate = "RetrieveUserInformation2/{hash}/{app=default}")]
public string RetrieveUserInformation2(string hash, string app)
{
return hash + " - " + app;
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
Console.WriteLine(c.DownloadString(baseAddress + "/RetrieveUserInformation/dsakldasda/Apple"));
Console.WriteLine();
c = new WebClient();
Console.WriteLine(c.DownloadString(baseAddress + "/RetrieveUserInformation/dsakldasda"));
Console.WriteLine();
c = new WebClient();
Console.WriteLine(c.DownloadString(baseAddress + "/RetrieveUserInformation2/dsakldasda"));
Console.WriteLine();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
關於使用查詢參數的UriTemplate
的默認值的補充答案。 @carlosfigueira提出的解決方案僅適用於根據文檔的路徑段變量。
只允許路徑段變量具有默認值。 查詢字符串變量,復合段變量和命名通配符變量不允許具有默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.