using System.ServiceModel; using System.Runtime.Serialization; namespace Service { [ServiceContract] public interface ISampleService { [OperationContract] [FaultContract(typeof(FaultMessage))] string SampleMethod(string msg); } [DataContract] public class FaultMessage { private string _errorTime; private string _errorMessage; [DataMember] public string ErrorTime { get { return this._errorTime; } set { this._errorTime = value; } } [DataMember] public string ErrorMessage { get { return this._errorMessage; } set { this._errorMessage = value; } } public FaultMessage(string time,string message) { this._errorTime = time; this._errorMessage = message; } } }
SampleService.cs的代码如下:
using System.ServiceModel; namespace Service { public class SampleService :ISampleService { public string SampleMethod(string msg) { if (msg.Length < 10) { return "输入的字符串为" + msg; } else { throw new FaultException<FaultMessage>( new FaultMessage("错误时间:" + System.DateTime.Now.ToString(), "输入的【" + msg + "】字符串大于10个字符")); } } } }
2. Host:控制台应用程序,服务承载程序。添加对程序集Service的引用,完成以下代码,寄宿服务。Program.cs代码如下:
logs_code_hide('eac1053d-5ee4-4393-909c-9c3a86db1ca6',event)" src="/Upload/Images/2015042710/2B1B950FA3DF188F.gif" alt="" />using System; using System.ServiceModel; using Service; namespace Host { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(SampleService))) { host.Opened += delegate { Console.WriteLine("服务已经启动,按任意键终止!"); }; host.Open(); Console.Read(); } } } }View Code
App.config代码如下:
<?xml version="1.0"?> <configuration> <system.serviceModel> <services> <service name="Service.SampleService" behaviorConfiguration="mexBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:1234/SampleService/"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="Service.ISampleService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="mexBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>View Code
我们通过svcutil.exe工具生成客户端代理类和客户端的配置文件
svcutil.exe是一个命令行工具,位于路径C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin下,我们可以通过命令行运行该工具生成客户端代理类
3. Client:控制台应用程序,客户端调用程序。将生成的UserInfoClient.cs和App.config复制到Client的工程目录下,完成客户端调用代码。Program.cs的代码如下:
using System; using System.ServiceModel; using Service; namespace Client { class Program { static void Main(string[] args) { SampleServiceClient proxy = new SampleServiceClient(); try { Console.WriteLine(proxy.SampleMethod("WCF")); Console.WriteLine(proxy.SampleMethod("Windows Communication Foundation")); } catch (FaultException<FaultMessage> ex) { Console.WriteLine(ex.Detail.ErrorTime+"\n"+ex.Detail.ErrorMessage); } finally { Console.Read(); } } } }
程序运行结果如下: