C#动态调用WCF时出错的问题
一.WCF应用程序:
1.接口:
namespace HSRHINIntf.Service
{
[ServiceContract]
public interface IRHINIntf
{
[OperationContract]
string HSTest(string s);
}
}
2.实现:
namespace HSRHINIntf.Service
{
public class RHINIntf : IRHINIntf
{
public string HSTest(string s)
{
return s + "张三";
}
}
}
二.exe宿主
1.App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<!--添加服务-->
<service name="HSRHINIntf.Service.RHINIntf" behaviorConfiguration="CalculatorServiceBehavior">
<!--name 必须与代码中的host实例初始化的服务一样
behaviorConfiguration 行为配置 -->
<host>
<baseAddresses>
<!--添加调用服务地址-->
<add baseAddress="http://localhost:8000/webservice/RHINIntf"/>
</baseAddresses>
</host>
<!--添加契约接口 contract="WcfDemo.IService1" WcfDemo.IService1为契约接口 binding="wsHttpBinding" wsHttpBinding为通过Http调用-->
<endpoint address="" binding="wsHttpBinding" contract="HSRHINIntf.Service.IRHINIntf"></endpoint>
</service>
</services>
<!--定义CalculatorServiceBehavior的行为-->
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
2.启用服务的代码:
ServiceHost host = null;//定义 ServiceHost
private void btnStart_Click(object sender, EventArgs e)
{
//WcfDemo.Service1 为引用的dll中的服务
host = new ServiceHost(typeof(HSRHINIntf.Service.RHINIntf));
host.Open();//启动服务
this.lbStatus.Text = "WCF服务已启动...";
}
三.客户端调用
private void button1_Click(object sender, EventArgs e)
{
//定义参数
string[] args = new string[1];
args[0] = "";
//调用接口
object o = InvokeWebService("http://localhost:8000/webservice/RHINIntf?wsdl", "RHINIntf", "HSTest", args);
MessageBox.Show(o.ToString());
}
//调用函数,返回函数执行结果
public static object InvokeWebService(string url, string classname, string methodname, object[] args)
{
string @namespace = "HSRHINIntf.Service";
//获取Web Service描述
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url); //这里指定你自己的web service url,一定要以?WSDL结尾
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.ProtocolName = "soap";