解决.NET WebService引用后添加HTTP Header的问题

麻蛋,搜索了好久,找到的都是对soap header的操作,不是对WebService的HTTP Header的操作,这是两种不同的概念,平常我们发起的WebService请求走的都是http通信协议,POST方式的请求,请求体是发送对象的SOAP结构。算了直接上答案。只不过还是英语不好

http://stackoverflow.com/questions/897782/how-to-add-custom-http-header-for-c-sharp-web-service-client-consuming-axis-1-4

上面是源地址,貌似有两种方法,一种是排名第一的

添加一下代码:

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
  System.Net.WebRequest request = base.GetWebRequest(uri);
  request.Headers.Add("myheader", "myheader_value");
  return request;
}

网上查了一天愣是没有找到有用的完整的demo,费了半天劲,实在找不到该插入那个地方啊,试遍了自动生成的Reference.cs里的任何位置,都不对,关键是winform 里面引用完成接口之后还找不到Reference.cs 文件。

第二种方式:最好是把using 去掉,要不出错都不知道哪里报错了。

static void Main(string[] args)
       {
           //wsAuth:就是自动生成的WebService服务的别名
           using (wsAuth.WsAuthenticationClient client = new wsAuth.WsAuthenticationClient())
           {
               using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
               {
                   var httpRequestProperty = new HttpRequestMessageProperty();
                   httpRequestProperty.Headers["ws-lala"] = "111";
                   httpRequestProperty.Headers["ws-lala11"] = "222";
                   OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
 
                   var cc = client.login("tlzzu", "123456");
               }
           }
       }

  去掉了using之后的测试实例,亲测有用

public string ces(string xml)
        {
            try
            {
                ceshi.RegistryAddRequestImplServiceClient client = new ceshi.RegistryAddRequestImplServiceClient();
                OperationContextScope scope = new OperationContextScope(client.InnerChannel);
                var httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers["username"] = "py";
                httpRequestProperty.Headers["password"] = "py";
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                var cc = client.HIPMessageServer("PatientRegistryAddRequest", xml);
            }
            catch (Exception ec)
            {

            }

            return "";
        }

  以上方式方法最后生成的xml   Headers 表头的样式是,在xml 最上面, Headers:{内容}

有可能不是想要的,有可能想要的是< Headers><username></username></ Headers> 这种 。这样的话就要用下面提供的方法了

经过测试可用:

新建一个类文件:取名WSHelper.cs   “名字随意”

里面添加这么一个方法属性:

public class RequestSOAPHeader : System.Web.Services.Protocols.SoapHeader
        {
            public string username { get; set; }
            public string password { get; set; }
        }

  这个方法里面定义Headers 里面的内容   Headers 一般都是表头验证,一般存用户名和密码  这样的生成完之后就是:< Headers><username></username><password></password></ Headers>

下面是具体的方法;

        public string webserivice(object obj, string path)
        {
            try
            {
                string xml1 = string.Empty;
                RegistraAddRequest.RegistryAddRequestImplServiceClient client = new RegistraAddRequest.RegistryAddRequestImplServiceClient();
                OperationContextScope scope = new OperationContextScope(client.InnerChannel);

                //实例化刚才创建的类文件,并且给类里面的两个属性赋值。
                WSHelper.RequestSOAPHeader RequestSOAPHeader = new WSHelper.RequestSOAPHeader();
                RequestSOAPHeader.username = "xiaoming";
                RequestSOAPHeader.password = "8504051434B74359A005E640AF40A8CD";
                //创建具有指定数据的新消息头。
                MessageHeader aMessageHeader = MessageHeader.CreateHeader("RequestSOAPHeader", "http://tempuri.org", RequestSOAPHeader);
                //将指定的消息头添加到集合
                OperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader);

                //以上是引用接口添加Header表头验证的方法,下面都是我业务需要自己的代码了。
                XDocument document = XDocument.Load(path);
                string xml = base64jm(document.ToString());
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(GenerateXml._basePath + "\xml模板\waibuModel.xml");
                Entity.CheckReport entity = obj as Entity.CheckReport;
                xml1 = xmlDoc.InnerXml.Replace("[XML内容]", xml);
                xml1 = xml1.Replace("[全球唯一标识]", Guid.NewGuid().ToString("D"));
                xml1 = xml1.Replace("[身份证号]", entity.IdCardCode);
                xml1 = xml1.Replace("[患者姓名]", entity.name);
                xml1 = xml1.Replace("[卡号]", entity.specimenCode);
                xml1 = xml1.Replace("[医院编码]", entity.fileSaveOrganizationCode);
                xml1 = xml1.Replace("[医院名称]", entity.fileSaveOrganizationName);
                xml1 = xml1.Replace("[省份]", "暂无");
                xml1 = xml1.Replace("[地市]", "暂无");
                xml1 = xml1.Replace("[市县]", "暂无");
                xml1 = xml1.Replace("[乡镇]", "暂无");
                xml1 = xml1.Replace("[街道]", "暂无");
                xml1 = xml1.Replace("[小区]", "暂无");
                xml1 = xml1.Replace("[时间]", entity.diagnoseDate.ToString("yyyy-MM-dd'T'HH:mm:ssZ"));
                xml1 = xml1.Replace("[服务名称]", entity.checkWayName + "服务");
                xml1 = xml1.Replace("[医生姓名]", entity.checkDoctorCode);
                // 得到根节点bookstore

                // 得到根节点的所有子节点

                var cc = client.HIPMessageServer("ProvideAndRegisterDocumentSet-b", xml1);
            }
            catch (Exception ec)
            {

            }
            return "";
        }

  

原文地址:https://www.cnblogs.com/zcwry/p/webservice_Header.html