5

我正在实现自定义 WCF REST 行为,它实现/覆盖基本 WebHttpBehavior,但允许使用自定义序列化程序进行 REST 通信。该代码基于 Carlos在此处的工作。

我已经让它运行了,但问题是我们真的很想使用 UriTemplate 功能来允许真正的 REST-ful URI。有没有人看到这样做或可以提供帮助以找到正确的实施?

我们坚持使用 WCF 是为了同时提供 REST 和 SOAP 端点,因此这里不能选择迁移到 Web API。

4

2 回答 2

0

我已经开始走上实现自己的UriTemplate解析/匹配逻辑的道路,但后来我偶然发现了这个答案(使用自定义 WCF 正文反序列化而不更改 URI 模板反序列化)并发现它确实做到了。

为了使用它,您仍然必须取消注释与验证 aUriTemplate未使用相关的代码。为了我的目的,我最终还重新格式化了代码(取出逻辑来检查是否有多个参数,因为在我的用例中,主体总是恰好是一个参数)。

于 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);
    //}
}

添加UriTemplatetoGetPerson或其他方法:

[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 回答