WCF - 如何在每个Web请求上添加自定义SoapHeader?

时间:2013-02-13 16:22:38

标签: wcf web-services soap-client soapheader

我想在客户端/用户的每个Web请求中将客户端地址头(客户端的IP地址)添加到SOAP Header。

我使用WCF服务,我的实现类如下:

public class Service : IService
{
    public Guid UserId()
    {
        if (MemUser != null)
            return (Guid)MemUser.ProviderUserKey;
        else
            return Guid.Empty;
    }
    public void SystemLog(Nullable<Guid> Customer, ResultCode Result, FacilityCode Facility, int Code, string Info)
    {
        // get IP address out of the SOAP header, if any
        string clientAddress = string.Empty;
        if ((ClientAddress != null) && !String.IsNullOrEmpty(ClientAddress.IPAddress))
            clientAddress = ClientAddress.IPAddress;
        else if ((HttpContext.Current != null) && (HttpContext.Current.Request != null) && !String.IsNullOrEmpty(HttpContext.Current.Request.UserHostAddress))
        clientAddress = HttpContext.Current.Request.UserHostAddress;

        SystemLog(Customer, Result, Facility, Code, Info, clientAddress); //writes into database
    }
//other methods
}

我的界面如下所示:

[ServiceContract(Name = "ServiceSoap", Namespace = "http://www.example.com/webservice"), XmlSerializerFormat]
public interface IService
{
    [OperationContract(Action = "http://www.example.com/webservice/UserId")]
    Guid UserId();

    //other implementations
}

如果我有一个由SoapHeader继承的ClientAddressHeader类,如

public class ClientAddressHeader : SoapHeader
{
    public string IPAddress;
    public ClientAddressHeader(){}
}

我可以使用[WebMethod]轻松传递wse中的SOAP头(ClientAddress),如:

[WebService(Namespace = "http://www.example.com/webservice")]
public class Service : System.Web.Services.WebService
{
    public ClientAddressHeader ClientAddress;

    [WebMethod, SoapHeader("ClientAddress", Direction = SoapHeaderDirection.In)] //client request
    public Guid UserId()
    {
        if (MemUser != null)
            return (Guid)MemUser.ProviderUserKey;
        else
            return Guid.Empty;
    }
}

所以有人知道我在使用WCF时如何传递SoapHeader?

如果有人向我解释如何实现这一目标,我真的很感激。

PS:我还在msdn和Agent Message Inspector中读过一些博客。这些博客对我来说都没有用,或者我对此并不了解。

0 个答案:

没有答案