我能走到今天,得益于2GDev的评论。代码没有正确处理异常或异常情况。
这样我可以使用生成的存根的端点(从而重用配置等)
public void CallWs()
{
WsdlRDListProductsPortTypeClient client = new WsdlRDListProductsPortTypeClient();
String req = "<Root xmlns=\"urn:ns\"><Query><Group>TV</Group><Product>TV</Product></Query></Root>";
CallWs(client.Endpoint, "ListProducts", GetRequestXml(req));
}
public XmlElement CallWs(ServiceEndpoint endpoint, String operation, XmlElement request)
{
String soapAction = GetSoapAction(endpoint, operation);
IChannelFactory<IRequestChannel> factory = null;
try
{
factory = endpoint.Binding.BuildChannelFactory<IRequestChannel>();
factory.Open();
IRequestChannel channel = null;
try
{
channel = factory.CreateChannel(endpoint.Address);
channel.Open();
Message requestMsg = Message.CreateMessage(endpoint.Binding.MessageVersion, soapAction, request);
Message response = channel.Request(requestMsg);
return response.GetBody<XmlElement>();
}
finally
{
if (channel != null)
channel.Close();
}
}
finally
{
if (factory != null)
factory.Close();
}
}
private String GetSoapAction(ServiceEndpoint endpoint, String operation)
{
foreach (OperationDescription opD in endpoint.Contract.Operations)
{
if (opD.Name == operation)
{
foreach (MessageDescription msgD in opD.Messages)
if (msgD.Direction == MessageDirection.Input)
{
return msgD.Action;
}
}
}
return null;
}
当我尝试这个来自MSDN http://msdn.microsoft.com/en-us/library/ms734712.aspx
基本ICalculator样品,其固定用SPNego,我必须改变这一点,因为那样我们需要一个IRequestSessionChannel而不是一个IRequestChannel。
public XmlElement CallWs(ServiceEndpoint endpoint, String operation, XmlElement request)
{
String soapAction = GetSoapAction(endpoint, operation);
IChannelFactory<IRequestSessionChannel> factory = null;
try
{
factory = endpoint.Binding.BuildChannelFactory<IRequestSessionChannel>();
factory.Open();
IRequestSessionChannel channel = null;
try
{
channel = factory.CreateChannel(endpoint.Address);
channel.Open();
Message requestMsg = Message.CreateMessage(endpoint.Binding.MessageVersion, soapAction, request);
Message response = channel.Request(requestMsg);
return response.GetBody<XmlElement>();
}
finally
{
if (channel != null)
channel.Close();
}
}
finally
{
if (factory != null)
factory.Close();
}
}
它所做的谈判,和消息似乎被发送,但不幸的是我现在得到了以下错误消息:
No signature message parts were specified for messages with the 'http://Microsoft.ServiceModel.Samples/ICalculator/Add' action.
这是一个REST服务?如果是这样,那么你可以直接使用WebClient。 – alf
不,这是一个基于NetTCP的SPNego等SOAP服务。手动操作太复杂了。 我做了类似的事情,我想使用Axis2服务客户端,但不幸的是Axis2不支持SPNego,所以我试图在.NET中创建一些通用的调用WCF服务以避免互操作性问题。 编辑:更多解释+打字 –
我正在寻找一种方法来解决您的问题,并发现这: http://social.msdn.microsoft.com/forums/en-US/wcf/thread/ad917cdd-60d4- 404c-a529-10597ff1bbf8/ 这可能是一个解决方案...使用该消息并将其传递到一个通道让你 选择如何格式化消息。 这里有一个Message.Create的例子 http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/7893/ – 2GDev