我已经试过了
Optional Parameters in WCF Service URI Template? Posted by Kamal Rawat in Blogs | .NET 4.5 on Sep 04, 2012 This section shows how we can pass optional parameters in WCF Servuce URI inShare
和
Optional query string parameters in URITemplate in WCF
但对我来说什么都不管用。下面是我的代码:
[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. 发布于 2013-03-09 01:36:47
对于此场景,您有两种选择。您可以在{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();
}
}发布于 2016-11-18 18:16:01
关于使用查询参数的UriTemplate中的默认值的补充答案。根据the docs,@carlosfigueira提出的解决方案仅适用于路径段变量。
只允许路径段变量具有默认值。查询字符串变量、复合段变量和命名通配符变量不允许具有默认值。
https://stackoverflow.com/questions/15289120
复制相似问题