正在设置使用WebHttpBinding的WCF服务…我可以将方法中的复杂类型返回为xml ok。如何将复杂类型作为参数?

[ServiceContract(Name = "TestService", Namespace = "http://www.test.com/2009/11")]
public interface ITestService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
               BodyStyle = WebMessageBodyStyle.Bare,
               UriTemplate = "/Person/{customerAccountNumber}, {userName}, {password}, {PersonCriteria}")]
    Person SubmitPersonCriteria(string customerAccountNumber,
                                string userName,
                                string password,
                                PersonCriteria details);
}

既然uritemplate只允许字符串,那么最佳实践是什么?这个想法是,客户端应用程序将向服务发送一个请求,类似于对某人的搜索条件。服务将使用适当的对象响应,该对象将数据作为xml包含。

最佳答案

可以使用rest发布复杂类型。

[ServiceContract]
public interface ICustomerSpecialOrderService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "deletecso/")]
    bool DeleteCustomerOrder(CustomerSpecialOrder orderToDelete);
}

实现如下所示:
public bool DeleteCustomerOrder(CustomerSpecialOrder orderToDelete)
{
    // Do something to delete the order here.
}

可以从wpf客户端调用方法:
public void DeleteMyOrder(CustomerSpecialOrder toDelete)
{
    Uri address = new Uri(your_uri_here);
    var factory = new WebChannelFactory<ICustomerSpecialOrderService>(address);
    var webHttpBinding = factory.Endpoint.Binding as WebHttpBinding;
    ICustomerSpecialOrderService service = factory.CreateChannel();
    service.DeleteCustomerOrder(toDelete);
}

或者也可以用httpwebrequest调用它,将复杂类型写入字节数组,这是我们从移动客户端执行的操作。
private HttpWebRequest DoInvokeRequest<T>(string uri, string method, T requestBody)
{
    string destinationUrl = _baseUrl + uri;
    var invokeRequest = WebRequest.Create(destinationUrl) as HttpWebRequest;
    if (invokeRequest == null)
        return null;

    // method = "POST" for complex types
    invokeRequest.Method = method;
    invokeRequest.ContentType = "text/xml";

    byte[] requestBodyBytes = ToByteArray(requestBody);
    invokeRequest.ContentLength = requestBodyBytes.Length;


    using (Stream postStream = invokeRequest.GetRequestStream())
        postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);

    invokeRequest.Timeout = 60000;

    return invokeRequest;
}

07-27 13:59