服务端:
namespace WcfServiceFist
{
[ServiceContract]
public interface IServiceFirst
{
[OperationContract]
double GetSum(int x, double y);
[OperationContract]
int GetX();
}
[DataContract]
public class CompositeType
{
[DataMember]
public int X { get; set; }
[DataMember]
public double Y { get; set; }
public double Sum()
{
return X + Y;
}
}
}
namespace WcfServiceFist
{
public class ServiceFirst : IServiceFirst
{
CompositeType Com = new CompositeType();
public double GetSum(int x, double y)
{
Com.X = x;
Com.Y = y;
return Com.Sum();
}
public int GetX()
{
return Com.X;
}
}
}
创建一个宿主程序,比如winform
创建一个Config
<configuration>
<system.serviceModel>
<services>
<service name="WcfServiceFist.ServiceFirst" behaviorConfiguration="WcfServiceFist.ServiceFirstBehavior">
<host>
<baseAddresses>
<!--添加服务调用地址-->
<add baseAddress="http://192.168.0.10:8200/">
</baseAddresses>
</host>
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="WcfServiceFist.IServiceFirst">
<!--
部署时,应删除或替换下列标识元素,以反映
用来运行所部署服务的标识。删除之后,WCF 将
自动推断相应标识。
-->
<identity>
<dns value="192.168.0.10"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfServiceFist.ServiceFirstBehavior">
<!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
<serviceMetadata httpGetEnabled="true"/>
<!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
配置文件:
<service name="WcfServiceFist.ServiceFirst" behaviorConfiguration="WcfServiceFist.ServiceFirstBehavior">
<endpoint address="" binding="wsHttpBinding" contract="WcfServiceFist.IServiceFirst">
<behavior name="WcfServiceFist.ServiceFirstBehavior">
在宿主程序中添加打开服务与关闭服务的功能
private ServiceHost _ServiceHost = new ServiceHost(typeof(WcfServiceFist.ServiceFirst));
private void btnOpen_Click(object sender, RoutedEventArgs e)
{
if (_ServiceHost.State != CommunicationState.Opened)
{
try
{
_ServiceHost.Open();
MessageBox.Show("打开成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
if (_ServiceHost.State != CommunicationState.Closed)
{
try
{
_ServiceHost.Close();
MessageBox.Show("关闭成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
打开服务之后,创建一个客户端,把
http://192.168.0.10:8200/作为服务引用的地址(服务端得开启并打开),添加服务引用。
这样之后就跟webservice使用方法一致了
private void button1_Click(object sender, EventArgs e){
ServiceFirstClient sfc = new ServiceFirstClient();
MessageBox.Show(sfc.GetSum(10, 10.9).ToString()); //结果20.9
MessageBox.Show(sfc.GetX().ToString()); //结果10
}