[英]How to modify SOAP headers on every method call
我為WCF服務提供了一個包裝器,該包裝器具有許多方法。 在每種方法上,我都要插入一個sessionId
和一個deviceId
進行身份驗證。 這些值會在實例化時更改,並且應該在完成后將其處置。
我知道您可以執行以下操作來修改呼叫的標頭:
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
}
您可能正在尋找的是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());
}
在發送每條消息之前(如方法名稱所示),它將相應地修改標頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.