一个简单的WCF实例
在学习WCF的相关知识,写了一个非常简单的例子。
项目结构如下:
Super.Wdxt.School.Contract 类库程序,定义服务契约(主要是一些接口),引用Super.Wdxt.School.Entity ;
Super.Wdxt.School.Entity 类库程序,一些实体
Super.Wdxt.School.Services 类库程序,提供对WCF服务的实现,也就是Contract项目中的接口实现类,引用Super.Wdxt.School.Entity,Super.Wdxt.School.Contract 。
Super.Wdxt.School.Hosting WEB应用程序,WCF的宿主程序,你可以使用不同的宿主程序比如控制台,winForm等等。引用上面三项.
Super.Wdxt.School.Web WEB应用程序,客户端程序。
1.创建实体类UserInfo.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Super.Wdxt.School.Entity { public class UserInfo { public int Id { get; set; } public string Name { get; set; } } }
2.创建服务契约IUser.cs
记得添加引用 using System.ServiceModel; using System.ServiceModel.Web;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Super.Wdxt.School.Entity; using System.ServiceModel; using System.ServiceModel.Web; namespace Super.Wdxt.School.Contract { [ServiceContract] public interface IUser { [OperationContract] string GetName(int id); [OperationContract] List<UserInfo> GetList(); } }
3.宿主环境
在Super.Wdxt.School.Hosting 添加新项-选择Wcf服务
删除其.cs文件,更改User.svc如下:
<%@ ServiceHost Language="C#" Debug="true" Service="Super.Wdxt.School.Services.User" CodeBehind="Super.Wdxt.School.Services.User.cs" %>
更改Web.config中system.serviceModel节点如下:
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="Super.Wdxt.School.Hosting.UserBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="Super.Wdxt.School.Hosting.UserBehavior" name="Super.Wdxt.School.Services.User"> <endpoint address="" binding="wsHttpBinding" contract="Super.Wdxt.School.Contract.IUser"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> </system.serviceModel>
4.Super.Wdxt.School.Web 中选择添加服务--点击发现
确定。在Default后台页面使用如下:
using (ServiceReference1.UserClient obj = new Super.Wdxt.School.Web.ServiceReference1.UserClient()) { string aa = obj.GetName(1); Response.Write(aa); }