问题描述
正在设置使用 webHttpBinding 的 WCF 服务...我可以从该方法中以 XML 格式返回复杂类型.如何将复杂类型作为参数?
Setting up a WCF service that uses the webHttpBinding... I can return complex types from the method as XML ok. How do I take in a complex type as a parameter?
[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 形式的数据的适当对象进行响应.
Since the UriTemplate only allows strings, what's the best practice? The idea is the client app will post a request to the service like search criteria for a person. The service will respond with the appropriate object containing the data as XML.
推荐答案
您可以使用 rest 发布复杂类型.
You can post complex types using 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 客户端调用方法:
You can call a method from a WPF client:
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 调用它,将复杂类型写入我们从移动客户端执行的字节数组.
Or you can call it with a HttpWebRequest as well, writing the complex type to a byte array which we do from a mobile client.
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;
}
这篇关于涉及复杂类型的 WCF Rest 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!