使用WebGet的可选UriTemplate参数

时间:2013-03-08 07:48:16

标签: c# wcf rest

我试过这些

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.  

2 个答案:

答案 0 :(得分:49)

此方案有两种选择。您可以在*参数中使用通配符({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();
    }
}

答案 1 :(得分:3)

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

  

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

相关问题