使用WebGet的可选UriTemplate参数

我试过这些

WCF服务URI模板中的可选参数? Kamal Rawat在博客中发表| 2012年9月4日的.NET 4.5本节介绍如何在WCF Servuce URI inShare中传递可选参数

WCF中URITemplate中的可选查询字符串参数

但没有什么对我有用。 这是我的代码:

[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提出的解决方案仅适用于根据文档的路径段变量。

只允许路径段变量具有默认值。 查询字符串变量,复合段变量和命名通配符变量不允许具有默认值。