建立第一个wcf程序
2017-09-27 11:13
267 查看
使用管理员权限启动vs (否者将导致ServiceHost开启失败 权限不足)
1.创建一个空的控制台程序
2.添加程序集引用 System.ServiceModel
3.写入一些代码 如下
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace HelloWCF { [ServiceContract] interface IHelloWCF { [OperationContract] string HelloWCF(); } public class HelloWCF : IHelloWCF { string IHelloWCF.HelloWCF() { return "HelloWCF"; } } }
这样便创建了一个wcf的服务接口
接下来需要绑定一个host并开启服务
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; using System.ServiceModel.Description; namespace HelloWCF { class Program { static void Main(string[] args) { Uri baseAddress = new Uri("http://192.168.5.14/MyService"); ServiceHost host = new ServiceHost(typeof(HelloWCF), baseAddress); host.AddServiceEndpoint(typeof(IHelloWCF), new WSHttpBinding(), "HelloWCF"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); host.Open(); Console.WriteLine("已开启"); Console.ReadLine(); host.Close(); Console.WriteLine("已关闭"); Console.ReadLine(); } } }
Uri baseAddress = new Uri("http://192.168.5.14/MyService"); 创建一个url对象用于绑定寄托的host地址
ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); 创建一个服务元数据行为对象 然后把它加入到宿主ServiceHost 对象的行为集合中去,这样元数据交换就被打开了
smb.HttpGetEnabled = true; 设置服务允许使用get请求
这样服务端便绑定完成
启动控制台程序 另外打开一个vs编辑器 创建一个空的控制台程序 下面将演示客户端调用服务过程
为项目添加服务引用
添加引用
添加后会生成一个服务文件 里面有一些class class中包含我们的服务 调用方式即调用函数 接收出参
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloWCFClient { class Program { static void Main(string[] args) { var client= new HelloWCFClient.HelloWCF.HelloWCFClient(); string result= client.HelloWCF(); Console.WriteLine(result); client.Close(); Console.Read(); } } }
这样就创建了一个wcf服务
相关文章推荐
- 我的第一个WCF程序
- WCF(2)我的第一个WCF程序,(解决方案结构、服务契约定义、服务契约定义等)
- cuda第0课环境配置+建立第一个程序:cuda4.2+VS2010+GeForce8500GT
- Remoting系列(二)----建立第一个入门程序
- 用IAR开发第一个程序,点亮led灯以及建立工程的步骤。
- 在Eclipse中建立第一个Servlet程序
- 基于vs08配置GLUT和建立我们第一个OpenGL程序
- Myeclipse建立第一个java web程序
- WCF入门教程2——创建第一个WCF程序
- 【学习】我的第一个WCF程序,Hello
- javascript 基础篇1 什么是js 建立第一个js程序
- 建立你的第一个WebMatrix程序
- 是时候在Eclipse中建立第一个Servlet程序了!
- 建立第一个directX程序——在C#下利用DirectSound实现声音播放
- 建立第一个directX程序——在C#下利用DirectSound实现声音播放
- WCF教程系列(1)-创建第一个WCF程序
- javascript 基础篇1 什么是js 建立第一个js程序
- WCF 入门教程一(动手新建第一个WCF程序并部署)
- WCF教程系列(1)-创建第一个WCF程序
- WCF学习----我的第一个WCF程序