微信小程序> WCF小程序案例以及序列化的使用

WCF小程序案例以及序列化的使用

浏览量:587 时间: 来源:weixin_34195546

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleTest
{
   class Program
   {
       static void Main(string[] args)
       {
           //发布服务端的主机服务
           string url = "http://localhost:8080";
           ServiceHost sh = new ServiceHost(typeof(MyService));
           Binding bind = new BasicHttpBinding();
           sh.AddServiceEndpoint(typeof(IService), bind, url);
           sh.Open();

           //客户端发送消息,使用服务端的服务
           ChannelFactoryIService cf = new ChannelFactoryIService(bind);
           EndpointAddress ea = new EndpointAddress(url);
           IService iservice = cf.CreateChannel(ea);
           Student ss = iservice.GetStudent();
           Console.WriteLine(ss.StuID);
           Console.WriteLine(ss.Name);
           Console.WriteLine(ss.Age);
           Console.Read();
       }
   }

   /// summary
   /// 定义服务的协定接口
   /// /summary
   [ServiceContract]
   public interface IService
   {
       [OperationContract]
       Student GetStudent();
   }

   /// summary
   /// 实现服务接口
   /// /summary
   public class MyService : IService
   {
       public Student GetStudent()
       {
           Student s = new Student();
           s.StuID = 123456;
           s.Name = "哈哈哈哈";
           s.Age = 20;
           return s;
       }
   }

   /// summary
   /// 序列化
   /// /summary
   [DataContract]
   public class Student
   {
       private long stuID;
       [DataMember]
       public long StuID
       {
           get { return stuID; }
           set { stuID = value; }
       }

       private string name;
       [DataMember]
       public string Name
       {
           get { return name; }
           set { name = value; }
       }

       private int age;
       [DataMember]
       public int Age
       {
           get { return age; }
           set { age = value; }
       }

       /// summary
       /// 反序列化时,执行此方法
       /// /summary
       /// param name="ss"/param
       [OnSerializing]
       public void hhha(StreamingContext ss)
       {
           this.Age = this.Age == 20 ? 50 : 88;
       }

   }


}

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

最新资讯

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎