1 新建空解决方案WCFServiceExp。
在解决方案下面新建Windows应用程序WCFClient和WCF服务应用程序WCFService。
程序完工后的结构如下图所示。
2 实现WCFService
新建WCF服务应用程序WCFService
在解决方案上右击--选择“添加”--选择“新建项目”--在已安装的模板中选择“WCF”--选择“WCF服务应用程序”
采用模板新建的WCFService结构如下图所示。
将WCFService下面的IService1.cs重命名为IExampleService.cs,将Service1.svc重命名为ExampleService.svc。
修改IExampleService.cs中提供的示例代码,得到下面的代码。
using System.ServiceModel; namespace WCFService { [ServiceContract] public interface IExampleService { [OperationContract] string GetMessage(string yourName); } }
修改ExampleService.svc中提供的示例代码,得到下面的代码。
namespace WCFService { public class ExampleService : IExampleService { public string GetMessage(string yourName) { if (string.IsNullOrEmpty(yourName)) { return "Hello,World!"; } else { return "Hello," + yourName + "!"; } } } }
此实例中提供的服务功能极其简单,仅向调用者返回一句欢迎信息。
修改Web.config文件,得到以下内容。
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <services> <service name="WCFService.ExampleService" behaviorConfiguration="ExampleServiceBeheavior"> <endpoint address="" binding="wsHttpBinding" contract="WCFService.IExampleService"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ExampleServiceBeheavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
在IIS下面新建虚拟目录WCFService,其对应的物理地址为G:\MyWork\WCFService。
在IIS中点开“网站”--右击“DefaultApp”--选择“添加应用程序”,在弹出窗体中进行设置。
发布WCFService。
右击WCFService--选择“发布”,在“发布Web”弹出窗口进行设置。发布方法选择“文件系统”,目标位置选择“G:\MyWork\WCFService”。点击“发布”进行发布。
发布完成后,打开浏览器,输入访问地址:http://localhost/WCFService/ExampleService.svc
访问后得到结果若与下图效果一致,则说明可以正确访问我们的WCF服务了。
3 使用SvcUtil.exe工具生成客户端调用类和配置文件
本人机器Win7环境,SvcUtil.exe所在的目录为:C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin(其他环境与该路径类似)
打开命令提示符工具,定位到SvcUtil.exe所在的目录,键入以下命令并执行。
SvcUtil.exe /out:D:\ExampleClient.cs /config:D:\App.config http://localhost/ExampleService.svc
生成完成后,你会在D盘根目录下找到文件ExampleClient.cs和App.config。
生成的ExampleClient.cs文件代码如下所示。
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成 // 运行时版本:2.0.50727.5477 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="IExampleService")] public interface IExampleService { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IExampleService/GetMessage", ReplyAction="http://tempuri.org/IExampleService/GetMessageResponse")] string GetMessage(string yourName); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] public interface IExampleServiceChannel : IExampleService, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] public partial class ExampleServiceClient : System.ServiceModel.ClientBase<IExampleService>, IExampleService { public ExampleServiceClient() { } public ExampleServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public ExampleServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ExampleServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ExampleServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public string GetMessage(string yourName) { return base.Channel.GetMessage(yourName); } }生成的 App.config 文件内容如下所示。
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IExampleService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="Message"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="http://localhost/WCFService/ExampleService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IExampleService" contract="IExampleService" name="WSHttpBinding_IExampleService"> <identity> <servicePrincipalName value="host/hp-HP" /> </identity> </endpoint> </client> </system.serviceModel> </configuration>
4 实现WCFClient
将SvcUtil.exe生成的文件ExampleClient.cs和App.config添加进WCFClient项目。
修改Program.cs文件代码,得到以下服务调用的代码。
using System; namespace WCFClient { class Program { static void Main(string[] args) { ExampleServiceClient exampleServiceClient = new ExampleServiceClient(); Console.WriteLine(exampleServiceClient.GetMessage(null)); Console.WriteLine(exampleServiceClient.GetMessage("")); Console.WriteLine(exampleServiceClient.GetMessage("tiana")); } } }
5 运行程序得到以下效果
至此,程序完工了。