我能走到今天,得益於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