建立一个类COOKIEMessageInspector,继承IClientMessageInspector,实现他的BeforeSendRequest和AfterReceiveReply两个方法。
public class COOKIEMessageInspector : IClientMessageInspector
{
private string SID { get; set; }
public COOKIEMessageInspector(string pSid)
{
SID = pSid;
}
public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
{
var COOKIE = "SID=" + SID;
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
if (string.IsNullOrEmpty(httpRequestMessage.Headers["COOKIE"]))
{
httpRequestMessage.Headers["COOKIE"] = COOKIE;
}
}
else
{
httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add("COOKIE", COOKIE);
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
return;
}
}