WCF服务端编写实例
1.通过VS新建WCF项目,生成一个接口文件和一个SVC.cs文件,SVC文件可以编写具体实现
2. 与一般程序的区别,主要是接口的定义。每一个方法的前面都要加上OperationContract修饰,否则访问不到:
using System.Collections.Generic;
using System.ServiceModel;
namespace WCFServiceGeneratedByConfig
{
[ServiceContract]
public interface IStudentService
{
[OperationContract]
string GetStudentFullName(int studentId);
[OperationContract]
IEnumerable<StudentInfo> GetStudentInfo(int studentId);
}
}
3. 完整代码写好后编译成dll
4. 配置
使用WCF Service Configuration Editor工具来配置,VS自带有这个软件,我们可以直接通过菜单->Tools->WCF Service Configuration Editor来打开。
首先,点击File->New config, 打开Service的Configuration界面。
然后,点击Create a new service…,在弹出的界面中,我们选择刚才生成的那个dll文件。双击之后,软件自动显示出了里面含有的Service:
点选那个Service,然后点击两次next,我们会看到出现了选择Communation Mode的界面,这里由于我们用的是net.tcp,所以我选择了第一个:TCP。
然后点击Next,我们会看到要我们填写EndPoint,这里我随便填写了一个:
之后,点击Next知道Finish,然后,我们的最基本的配置就结束了。
回到Config界面之后,我们点击Advanced->Service Behaviors->New Service Behavior Configuration,在弹出的界面中,我们点击Add->serviceMetadata:
然后点击Add,我们就添加了一个Behavior Element。点击刚刚生成的serviceMetadata节点,在显示的界面中,设置HttpGetEnabled为true。
然后点击原来的Service节点下的Host节点,在Base Address栏目下单击Add,添加如下的Base Address:
最后点击OK。然后点击菜单File->Save As 保存到项目文件夹下即可。
这里是生成的代码:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="StudentBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WCFServiceGeneratedByConfig.StudentService">
<endpoint address="net.tcp://127.0.0.1:50001/StudentServiceEndPoint"
binding="netTcpBinding" bindingConfiguration="" contract="WCFServiceGeneratedByConfig.IStudentService" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://127.0.0.1:50001/StudentServiceEndPoint" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
5. 生成好的config文件可以命名为App.config,可以放到要启动服务的程序项目文件夹下。比如新建一个控制台项目,将该文件放到项目文件夹下。编译控制台程序后,会在exe文件夹下生成一个exe.config文件,用于动态配置。