gpt4 book ai didi

c# - 使用 WebGet 的可选 UriTemplate 参数

转载 作者:IT王子 更新时间:2023-10-29 04:29:04 24 4
gpt4 key购买 nike

这些我都试过了

Optional Parameters in WCF Service URI Template?Posted by Kamal Rawat in Blogs | .NET 4.5 on Sep 04, 2012This section shows how we can pass optional parameters in WCF Servuce URIinShare

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.  

最佳答案

对于这种情况,您有两种选择。您可以在 {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();
}
}

关于c# - 使用 WebGet 的可选 UriTemplate 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15289120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com