如何在每个方法调用

时间:2017-03-10 23:02:39

标签: c# wcf soap request-headers

我有一个包含许多方法的WCF服务的包装器。在每个方法上,我都要插入sessionIddeviceId进行身份验证。这些值会在实例化时发生变化,您应该在完成后将其丢弃。

我知道你可以这样做来修改通话中的标题:

using (var scope = new OperationContextScope((IClientChannel)this.client.InnerChannel))
{
    WebOperationContext.Current.OutgoingRequest.Headers.Add("SessionId", this.sessionId);
    WebOperationContext.Current.OutgoingRequest.Headers.Add("DeviceKey", this.deviceKey.ToString());
    return this.client.MyMethod("call");
}

我不想粘贴20次。有没有办法干净地做到这一点?我可以使用Reflection并调用。但是我的方法没有统一的值和参数。

public class Service {
    private string sessionId; //needed for auth
    private string deviceId; // needed for auth
    public Service (string userName, string password) {}

    public string[] GetList() {}
    public Foo[] GetSomethingElse(Bar arg) {}
    public List<Baz> GetTheThing(Fez org) {}
    // etc... x 20
}

1 个答案:

答案 0 :(得分:0)

您所寻找的可能是IClientMessageInspector及其方法BeforeSendRequest

从这里你可以做这样的事情

public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
    HttpRequestMessageProperty prop;
    if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
    {
         prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
    }
    else
    {
         prop = new HttpRequestMessageProperty();
         request.Properties.Add(HttpRequestMessageProperty.Name, prop);
    }

    prop.Headers.Add("SessionId", this.sessionId);
    prop.Headers.Add("DeviceKey", this.deviceKey.ToString());

}

在发送每条消息之前(如方法名称所示),它将相应地修改标题。

唉,这里有关于如何注册实现此接口的类的链接link