zoukankan      html  css  js  c++  java
  • 重温WCF之发送和接收SOAP头(三)

    SOAP头可以理解为一种附加信息,就是附加到消息正文的内容。

    既然消息头是附加信息,那有啥用呢?你可别说,有时候还真有不少用处。举个例子,WCF的身份验证是不是很麻烦?还要颁发什么证书的(当然不是荣誉证书),如果只是验证一个客户端的身份,如用户名什么的,那么,在调用服务方法时,动态加入一些消息头,到了服务器端就获取并验证消息头。这样一来,是不是也实现身份验证?

    首先,实现服务器端,在OperationContract方法中通过OperationContext.Current.IncomingMessageHeaders就能得到从客户端收到的消息头了,记得引入System.ServiceModel命名空间。

    class Program
        {
            [ServiceContract]
            public interface IService1
            {
                [OperationContract]
                void HandlerHeader();
            }
    
            public class Service1 : IService1
            {
                public void HandlerHeader()
                {
                    int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("header", "http://www.yxl.com");
                    if (index != -1)
                    {
                        string hd = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(index);
                        Console.WriteLine("收到的标头:{0}", hd);
                    }
                }
            }
            static void Main(string[] args)
            {
                using (ServiceHost host = new ServiceHost(typeof(Service1)))
                {
                    host.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "http://127.0.0.1:8888/service1");
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl = new Uri("http://127.0.0.1:8888/service");  //httpGetUrl客户端引用的地址
                    host.Description.Behaviors.Add(behavior);
                    host.Opened += delegate
                    {
                        Console.WriteLine("服务已启动");
                        Console.ReadKey();
                    };
                    host.Open();
                }
            }

    客户端:

     using (Service1Client client = new Service1Client() )
                {
                    using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
                    {
                        MessageHeader header = MessageHeader.CreateHeader("header", "http://www.yxl.com", "你好,我发消息给你了");
                        OperationContext.Current.OutgoingMessageHeaders.Add(header);
                        client.HandlerHeader();
                        MessageBox.Show("服务方法已调用");
                    }
                }

    显示结果:

  • 相关阅读:
    git pull origin master命令后发生冲突
    计算属性和侦听器
    微信小程序 wx.navigateBack携带参数
    小程序----路由
    quill工具栏出现提示的功能
    quill修改字体大小
    quill报错,"RangeError: Maximum call stack size exceeded"
    quill添加字体
    新建一个vue项目(补充了vue-cli4.0快速搭建一个项目【站在巨人的肩膀上并亲测】)
    codeforce round 7
  • 原文地址:https://www.cnblogs.com/yxlblogs/p/3761597.html
Copyright © 2011-2022 走看看