创建SOAP标头?

时间:2010-10-19 14:23:07

标签: c# web-services api soap

如何添加创建SOAP Web服务标头?

示例

<soap:Header>
    <myHeader xmlns="https://www.domain.com">
        <Username>string</Username>
        <Password>string</Password>
    </myHeader>
</soap:Header>

源代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;


namespace TestWebServices
{
    /// <summary>
    /// Summary description
    /// </summary>
    [WebService(Namespace = "https://Test.com")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class Testing : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetTestValue()
        {


            return "xyz";
        }
    }

}

4 个答案:

答案 0 :(得分:4)

怎么样:

public class MyHeader : SoapHeader
{
    public string Username;
    public string Password;
}

这里有更多关于这个主题的内容:

  

Using SOAP Headers (MSDN)

     

Defining and Processing SOAP Headers (MSDN)

答案 1 :(得分:3)

如果你需要对soap header xml的渲染方式进行细粒度控制(当与用java编写的web服务接口时发生),你可以通过实现IXmlSerializable来覆盖所有渲染

[XmlRoot("customHeader", Namespace = "http://somecompany.com/webservices/security/2012/topSecret")]
public class customHeader: SoapHeader, IXmlSerializable
{
    public customHeader()
    {
        Actor = "http://schemas.xmlsoap.org/soap/actor/next";
        MustUnderstand = false;
    }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
        //throw new NotImplementedException();
    }

    public void ReadXml(XmlReader reader)
    {
        //throw new NotImplementedException();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("soap:actor", Actor);
        writer.WriteAttributeString("soap:mustUnderstand", MustUnderstand ? "1" : "0");
        writer.WriteRaw("some encrypted data");
        //get it exactly the way you want it in here without mucking with Xml* property attributes for hours on end
        //writer.WriteElement(...);
    }
}

答案 2 :(得分:0)

带有标题的SOAP消息可能如下所示:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

  <soap:Header>
    <Username>string</Username>
    <Password>string</Password>
  </soap:Header>

</soap:Envelope>

答案 3 :(得分:0)

EndpointAddressBuilder builder = new EndpointAddressBuilder(client.Endpoint.Address);
AddressHeader header = AddressHeader.CreateAddressHeader("apiKey", "http://tempuri.org", "longapikeyhere");

builder.Headers.Add(header);
client.Endpoint.Address = builder.ToEndpointAddress();