24

私はこれらを試しました

WCF サービス URI テンプレートのオプションのパラメーター? 投稿者 カマル・ラワット in ブログ | 2012 年 9 月 4 日の .NET 4.5 このセクションでは、WCF サービス 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.  
4

2 に答える 2

52

このシナリオには 2 つのオプションがあります。パラメータでワイルドカード ( *) を使用することもでき{app}ます。これは、「残りの URI」を意味します。{app}または、パーツが存在しない場合に使用されるデフォルト値をパーツに与えることができます。

URI テンプレートの詳細については、http://msdn.microsoft.com/en-us/library/bb675245.aspxを参照してください。以下のコードは両方の代替方法を示しています。

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();
    }
}
于 2013-03-08T17:36:46.667 に答える
3

UriTemplateクエリ パラメータを使用した s のデフォルト値に関する補足的な回答。@carlosfigueira によって提案されたソリューションは、 docsに従ってパス セグメント変数に対してのみ機能します。

デフォルト値を持つことができるのは、パス セグメント変数だけです。クエリ文字列変数、複合セグメント変数、および名前付きワイルドカード変数にデフォルト値を設定することは許可されていません。

于 2016-11-18T10:16:00.520 に答える