WCF学习问题记录
WCF火了很多年了,一直没有学习和关注过,换了个公司,新公司很多服务都是基于WCF,虽然我所在的项目组没用上,但是先学来准备。WCF的教程之类的多如牛毛,在此就不说了,今就记录我个人学习中遇到的问题,希望大牛们给小弟指出不足,提出保宝意见。
好了,正题吧。
当然开始操作前,你必须要引入程序集:System.ServiceModel
第一步:建WCF契约
using System.ServiceModel; namespace MYContact { [ServiceContract] public interface IContactTest { [OperationContract] int Add(int x, int y); } }
第二步:建立实现类
using MYContact; namespace MYService { public class MYService : IContactTest { public int Add(int x, int y) { return x + y; } } }
第三步:创建寄宿(使用的是控制台)
3.1步:先写程序吧
using System; using System.ServiceModel; namespace Service { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(MYService.MYService))) { host.Opened += (a, b) => { Console.WriteLine("Start ok"); }; host.Open(); } Console.ReadLine(); } } }
3.2 写配置文件(App.config)
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="mybehavior" > <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> <services> <service name="MYService.MYService" behaviorConfiguration="mybehavior"> <endpoint address="" binding="basicHttpBinding" contract="MYContact.IContactTest" /> <host> <baseAddresses> <add baseAddress="http://localhost:9887/testmethod"/> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration>
好了,这里我没用客户端,直接运行控制台程序,启动正常,但是问题来了,无论怎么也访问不了:http://localhost:9887/testmethod(结果:无法显示)
。。。。。。
咋办,然后一行一行的看代码,测试,都没发现问题,网上看别人的例子差不多,而且启动也没有报错。最后弄了好久,仔细再看代码,天啦,我的错。
using System; using System.ServiceModel; namespace Service { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(MYService.MYService))) { host.Opened += (a, b) => { Console.WriteLine("Start ok"); }; host.Open(); Console.ReadLine(); } // Console.ReadLine(); } } }
看起来是把一句 Console.ReadLine();位置写错了,看细看,是因为代码放在using中,当执行完using后,里面的内容会被自动释放,我。。。太丢人了,写了这么几年的程序,这个都没注意到。
以后坚持写博客,记录自己的失误,以备查看。
浙公网安备 33010602011771号