没有请求参数的函数调用的WCF SoapHeader

本文关键字:函数调用 SoapHeader WCF 参数 请求 | 更新日期: 2023-09-27 18:08:28

我有一个WCF服务,它从OperationContext.Current.RequestContext.RequestMessage接收输入,而不是从传入的任何参数接收输入。
我没有DataContract
请问如何实现SoapHeader ?

我的服务接口:

[ServiceContract(Namespace = Namespaces.Example)]
public interface IExample
{
    [OperationContract]
    string ExampleRequests();
}
服务:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, Namespace = Namespaces.Example)]
public class Example: IExample
{
      public string ExampleRequests(){...}
}


没有请求参数的函数调用的WCF SoapHeader

我已经使用https://wcfextras.codeplex.com/和SoapHeader属性来完成这个。

更新接口:


    [ServiceContract(Namespace = Namespaces.Example)]
    public interface IExample
    {
        [SoapHeader("MyHeader", typeof(MyHeader), Direction = SoapHeaderDirection.In)]
        [OperationContract]
        string ExampleRequests();
    }


更新服务:


    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, Namespace = Namespaces.Example)]
    public class Example: IExample
    {
        public string ExampleRequests()
        {
        ...
        MyHeader soapHeader = SoapHeaderHelper.GetInputHeader("MyHeader");
        if (soapHeader == null || soapHeader.Username.IsNullOrEmpty() || !ValidateCredentials(soapHeader))
        {
        return "You do not have permission to access this service";
        }
        ...
        }
        private bool ValidateCredentials(MyHeader soapHeader)
        {
        if (soapHeader.Username == "admin" && soapHeader.Password == "123")
        {
        return true; 
        }
        return false;
        }
    }

到了头类:


    [DataContract(Namespace = Namespaces.Example)]
    public class MyHeader
    {
        [DataMember]
        public string Username { get; set; }
        [DataMember]
        public string Password { get; set; }
    }