UriTemplates与自定义WCF 4.5 WebHttpBehavior

Bre*_*bst 5 .net c# rest wcf uritemplate

我正在实现自定义WCF REST行为,它实现/覆盖基本WebHttpBehavior,但允许使用自定义序列化程序进行REST通信.该代码基于卡洛斯在这里的工作.

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

我们故意坚持使用WCF同时提供REST和SOAP端点,因此转向Web API不是一种选择.

小智 -1

问题可能只是这个例子有点过时了。此外,实现类 显式NewtonsoftJsonBehavior重写并在方法InvalidOperationException内抛出 an Validate(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);
    //}
}
Run Code Online (Sandbox Code Playgroud)

添加一个UriTemplatetoGetPerson或其他方法:

[WebGet, OperationContract]
Person GetPerson();

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

在类中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" },
        },
    };
}
Run Code Online (Sandbox Code Playgroud)

在该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": [
{...},
{...}
}
Run Code Online (Sandbox Code Playgroud)