·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> Step by Step 创建一个WCF Service
原创地址:http://www.cnblogs.com/jfzhu/p/4025448.html
转载请注明出处
(1)创建WCF Service类库
创建一个Class Library的项目:
删除掉默认的Class1.cs文件,然后添加一个WCF Service项目:
Visual Studio会自动帮助你生成两个文件:HelloService.cs 和 IHelloService.cs,另外还自动添加了System.ServiceModel引用,它是WCF的核心。
修改IHelloService.cs和HelloService.cs文件。
IHelloService.cs:
namespace HelloService{ // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IHelloService" in both code and config file together. [ServiceContract] public interface IHelloService { [OperationContract] string GetMessage(string name); }}
HelloService.cs:
namespace HelloService{ // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "HelloService" in both code and config file together. public class HelloService : IHelloService { public string GetMessage(string name) { return "Hello " + name; } }}
(2)创建WCF的Host
添加一个新的asp.net Empty Web application:
添加一个新Item WCF Service
删除HelloService.svc.cs和IHelloService.cs文件。
添加HelloService Class Library的项目引用:
修改HelloService.svc为:
<%@ ServiceHost Language="C#" Debug="true" Service="HelloService.HelloService" %>
Web.config:
<?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <services> <service name="HelloService.HelloService" behaviorConfiguration="metaBehavior"> <endpoint address="HelloService" binding="basicHttpBinding" contract="HelloService.IHelloService"></endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> <host> <baseAddresses> <add baseAddress="http://localhost:8080"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="metaBehavior"> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel></configuration>
其中,service name=”命名空间.类名”,behaviorConfiguration是用来关联下面behavior的定义的。
endpoint address中定义的是相对地址,与baseAddress结合起来为完整地址
endpoint contract=”命名空间.接口名”
两个endpoint,第一个binding是basicHttpBinding,用于HTTP协议;第二个endpoint用于交换metadata,binding为mexHttpBinding。
其中behavior的定义是用来允许交换metadata的。
Build解决方案,如果没有错误就进行到下一步,部署WCF Service到IIS
(1)Publish HelloServiceIISHost项目
(2)部署到IIS
浏览HelloService.svc
添加一个服务引用: