5

カスタムの WCF REST 動作を実装しています。これは、基本 WebHttpBehavior を実装/オーバーライドしますが、カスタム シリアライザーを使用して REST 通信を可能にします。このコードは、Carlos のここでの作業に基づいています。

私はそれを実行しましたが、実際には UriTemplate 機能を使用して真の REST-ful URI を許可したいと考えています。誰かがこれを見たことがありますか、または適切な実装を見つけるための助けを提供できますか?

REST エンドポイントと SOAP エンドポイントを同時に提供するために意図的に WCF に固執しているため、ここでは Web API に移行することはできません。

4

2 に答える 2

0

私は独自のUriTemplate解析/照合ロジックを実装する道を歩み始めていましたが、この回答 ( Using Custom WCF Body Deserialization without changing URI Template Deserialization ) に出くわし、それ以上のことを行っていることがわかりました。

それを使用するには、 aUriTemplateが使用されていないことの検証に関連するコードのコメントを解除する必要があります。また、目的のためにコードを少し再フォーマットすることになりました(私のユースケースでは、本体は常に正確に1つのパラメーターになるため、複数のパラメーターがあるかどうかを確認するロジックを取り出します)。

于 2016-06-22T13:01:26.640 に答える
-1

問題は、例が少し古くなっていることかもしれません。また、実装クラスはメソッド内でNewtonsoftJsonBehavior明示的にオーバーライドしてスローしています。InvalidOperationExceptionValidate(ServiceEndpoint endpoint)

Carlos の例を使用して、検証を削除します。

public override void Validate(ServiceEndpoint endpoint)
{
    base.Validate(endpoint);

    //TODO: Stop throwing exception for default behavior.
    //BindingElementCollection elements = endpoint.Binding.CreateBindingElements();
    //WebMessageEncodingBindingElement webEncoder = elements.Find<WebMessageEncodingBindingElement>();
    //if (webEncoder == null)
    //{
    //    throw new InvalidOperationException("This behavior must be used in an endpoint with the WebHttpBinding (or a custom binding with the WebMessageEncodingBindingElement).");
    //}

    //foreach (OperationDescription operation in endpoint.Contract.Operations)
    //{
    //    this.ValidateOperation(operation);
    //}
}

またはその他のメソッドを追加しUriTemplateます。GetPerson

[WebGet, OperationContract]
Person GetPerson();

[WebGet(UriTemplate="GetPersonByName?l={lastName}"), OperationContract(Name="GetPersonByName")]
Person GetPerson(string lastName);

クラス内にService、単純な実装を追加して、引数が解析されることを検証します。

public Person GetPerson(string lastName)
{
    return new Person
    {
        FirstName = "First",
        LastName = lastName, // Return the argument.
        BirthDate = new DateTime(1993, 4, 17, 2, 51, 37, 47, DateTimeKind.Local),
        Id = 0,
        Pets = new List<Pet>
        {
            new Pet { Name= "Generic Pet 1", Color = "Beige", Id = 0, Markings = "Some markings" },
            new Pet { Name= "Generic Pet 2", Color = "Gold", Id = 0, Markings = "Other markings" },
        },
    };
}

このProgram.Main()メソッドでは、この新しい URL を呼び出すと、カスタム実装なしでクエリ文字列値が解析されて返されます。

[Request]
SendRequest(baseAddress + "/json/GetPersonByName?l=smith", "GET", null, null);

[Response]
{
"FirstName": "First",
"LastName": "smith",
"BirthDate": "1993-04-17T02:51:37.047-04:00",
"Pets": [
{...},
{...}
}
于 2014-09-24T15:45:04.803 に答える