首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用WebGet的可选UriTemplate参数

使用WebGet的可选UriTemplate参数
EN

Stack Overflow用户
提问于 2013-03-08 15:48:16
回答 2查看 44.6K关注 0票数 24

我已经试过了

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

但对我来说什么都不管用。下面是我的代码:

代码语言:javascript
复制
    [WebGet(UriTemplate = "RetrieveUserInformation/{hash}/{app}")]
    public string RetrieveUserInformation(string hash, string app)
    {

    }

如果参数被填满,它就会起作用:

代码语言:javascript
复制
https://127.0.0.1/Case/Rest/Qr/RetrieveUserInformation/djJUd9879Hf8df/Apple  

但如果app没有值,则不起作用

代码语言:javascript
复制
https://127.0.0.1/Case/Rest/Qr/RetrieveUserInformation/djJUd9879Hf8df  

我想让app成为可选的。如何做到这一点?

以下是当app没有值时的错误:

代码语言:javascript
复制
Endpoint not found. Please see the service help page for constructing valid requests to the service.  
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-09 01:36:47

对于此场景,您有两种选择。您可以在{app}参数中使用通配符(*),这意味着“URI的其余部分”;也可以为{app}部件提供一个默认值,如果该部件不存在,将使用默认值。

您可以在http://msdn.microsoft.com/en-us/library/bb675245.aspx上看到有关URI模板的更多信息,下面的代码显示了这两种选择。

代码语言:javascript
复制
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();
    }
}
票数 52
EN

Stack Overflow用户

发布于 2016-11-18 18:16:01

关于使用查询参数的UriTemplate中的默认值的补充答案。根据the docs,@carlosfigueira提出的解决方案仅适用于路径段变量。

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15289120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档