# C# 调用java的WebService添加SOAPHeader验证

C#调用java的WebService添加SOAPHeader验证


本文与别的网文不同的是,本文教大家利用VS添加WSDL自动生成的代理类添加SoapHeader。


写JAVA接口的同事给了一个文档,要求在soapHeader里面加一个UserToken的验证。JAVA处理这事情其实挺简单的,就配置一下配置文件就可以了。但C#不能简单的通过配置处理。

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.m3.mls.com/">
<soapenv:Header>	
	<Authentication>		
		<UserToken>EVQfaMqRNGpjmqdrKNjYvlKjVndyYcI4uUyj8OaT</UserToken>	
	</Authentication>
</soapenv:Header>
<soapenv:Body>	
	<web:getHRDeptInfo/>
</soapenv:Body>
</soapenv:Envelope>


操作步骤

  1. 添加Web引用
  2. 添加Authentication类
  3. 在自动生成的Reference.cs类添加Authentication全局变量
  4. 在访问的WebService方法上方添加SOAPHeader的声明
  5. 接口调用


1.添加Web引用

新版本的VS已经没有添加Web引用的菜单了。只有添加服务引用的选项


但可以在添加服务引用的高级选项中添加web引用。



PS:为什么不能添加服务引用呢? 因为添加服务引用不会自动生成WebService代理类。所以就没办法修改它的SoapHeader。

2.添加Authentication类

SoapHeader的参数不一定是UserToken,也有可能是账号密码。大家根据接口提供方给出的格式自行调整。

using System.Web.Services.Protocols;
public class Authentication : SoapHeader
{
    public string UserToken { get; set; }


    /// <summary>
    /// 构造函数
    /// </summary>
    public Authentication() { } 
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="usertoken">密码</param>
    public Authentication(string usertoken)
    {
        this.UserToken = usertoken;
    }
}


3.在自动生成的Reference.cs类添加Authentication全局变量


public Authentication Authentication;

4.在访问的WebService方法上方添加SOAPHeader的声明

同样是在WebService的代理类Reference.cs里里面添加代码,主要是添加[SoapHeader("Authentication")]这一段。

如果要更新接口的话,代理类里面的全局变量和声明记得重新添加。

    /// <remarks/>
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace="http://webservice.m3.mls.com/", ResponseNamespace="http://webservice.m3.mls.com/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    [return: System.Xml.Serialization.XmlElementAttribute("return", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [SoapHeader("Authentication")]
    public flow[] getHROAFlowInfo([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string tableName, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string tableColumn, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string columnValue) {
        object[] results = this.Invoke("getHROAFlowInfo", new object[] {
                    tableName,
                    tableColumn,
                    columnValue});
        return ((flow[])(results[0]));
    }
5.接口调用

IManuOrderServiceService proxy = new IManuOrderServiceService();
//指定SoapHeader验证
proxy.Authentication = new Authentication("W9nQcVGTynQnTewCcLYuGShAjhDjpoanKs4ON0");
var a = proxy.getManuOrderInfo("20170505-0030");
Console.WriteLine(a);


原文地址:https://www.cnblogs.com/neso520/p/12491259.html