是否可以在不使用NETCFSvcUtil生成代理的情况下与WCF服务进行通信?
我正在尝试使用紧凑框架在移动设备上调用WCF服务。 我不想使用NETCFSvcUtil为特定原因生成代理。
我在移动端有这个示例代码来测试它:
// This is the contract defined at the client side (mobile device)
public interface IService1
{
string GetData(int value);
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string address = "http://192.168.30.88:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/";
// It throws here ....
var channelFactory = CreateDefaultBinding().BuildChannelFactory<IService1>(new System.ServiceModel.Channels.BindingParameterCollection());
var channel = channelFactory.CreateChannel(new EndpointAddress(new Uri(address)));
var result = channel.GetData(5);
this.Text = result.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public static System.ServiceModel.Channels.Binding CreateDefaultBinding()
{
System.ServiceModel.Channels.CustomBinding binding = new System.ServiceModel.Channels.CustomBinding();
binding.Elements.Add(new System.ServiceModel.Channels.TextMessageEncodingBindingElement(System.ServiceModel.Channels.MessageVersion.Soap11, System.Text.Encoding.UTF8));
binding.Elements.Add(new System.ServiceModel.Channels.HttpTransportBindingElement());
return binding;
}
}
但是我得到了这个异常:请求了通道类型'CallingWCFFromDevice.IService1',但Binding'CustomBinding'不支持它,或者没有正确配置它来支持它。 参数名称:TChannel
了解发生了什么?我猜我没有正确使用BuildChannelFactory ......
答案 0 :(得分:0)
我不确定您对安全性有什么要求,但使用其中一个预定义的绑定(如BasicHttpBinding)可能更简单;这将使您的代码如下所示:
IService1 channel = null;
try {
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress("http://192.168.30.88:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/");
IChannelFactory<IService1> factory = binding.BuildChannelFactory<IService1>(new BindingParameterCollection());
channel = factory.CreateChannel(address);
// Use the channel here...
}
finally {
if(channel != null && ((ICommunicationObject)channel).State == CommunicationState.Opened) {
((ICommunicationObject)channel).Close();
}
}
在您对IService1的定义中,您不包含任何必需的属性,接口需要应用ServiceContractAttribute,并且接口中的方法需要应用OperationContractAttribute,如下所示:
[ServiceContract] public interface IService1
{
[OperationContract] string GetData(int value);
}