В отличие от веб-служб ASMX, которые привязаны к HTTP транспорта, WCF позволяет использовать различные транспортные протоколы. Поэтому не все параметры протокола (такие как Cookies для HTTP-транспорта) доступны в справочной службе WCF.
Вы можете, однако, добавить инспектор сообщений, который проверяет сообщения, отправленные между клиентом и сервером. Этот article описывает способ отправки файлов cookie на сервер.
Я расширил образец, чтобы использовать CookieContainer. Кроме того, следующий код показывает, как оценить заголовок Set-Cookie
, отправленный сервером, для добавления новых файлов cookie в контейнер. Обратите внимание, что образец показывает базовый контур, но может потребоваться расширение или еще одна проверка. Однако в простом сценарии это сработало.
В следующем фрагменте показан метод тестирования службы WCF, размещенной в IIS и интегрированной в структуру ASP.NET. Это в основном повторяет куки посылаются на сервер в виде строки и добавляет два новых:
public string GetData(int value)
{
var reply = string.Join(", ",
from x in HttpContext.Current.Request.Cookies.AllKeys
select x + "=" + HttpContext.Current.Request.Cookies[x].Value);
HttpContext.Current.Response.Cookies.Add(new HttpCookie("Test", "Test123"));
HttpContext.Current.Response.Cookies.Add(new HttpCookie("Test2", "Test1234"));
return reply;
}
Следующая тестовая программа создает CookieContainer для печенья, добавляет демо печенье и регистрирует новое поведение для конечной точки обслуживание:
class Program
{
static void Main(string[] args)
{
var cookieCont = new CookieContainer();
using(var svc = new TestServiceReference.TestServiceClient())
{
cookieCont.Add(svc.Endpoint.Address.Uri, new Cookie("TestClientCookie", "Cookie Value 123"));
var behave = new CookieBehavior(cookieCont);
svc.Endpoint.EndpointBehaviors.Add(behave);
var data = svc.GetData(123);
Console.WriteLine(data);
Console.WriteLine("---");
foreach (Cookie x in cookieCont.GetCookies(svc.Endpoint.Address.Uri))
Console.WriteLine(x.Name + "=" + x.Value);
}
Console.ReadLine();
}
}
поведение служит для добавления инспектора пользовательских сообщений и вручая CookieContainer:
public class CookieBehavior : IEndpointBehavior
{
private CookieContainer cookieCont;
public CookieBehavior(CookieContainer cookieCont)
{
this.cookieCont = cookieCont;
}
public void AddBindingParameters(ServiceEndpoint serviceEndpoint,
System.ServiceModel.Channels
.BindingParameterCollection bindingParameters) { }
public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint,
System.ServiceModel.Dispatcher.ClientRuntime behavior)
{
behavior.MessageInspectors.Add(new CookieMessageInspector(cookieCont));
}
public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint,
System.ServiceModel.Dispatcher
.EndpointDispatcher endpointDispatcher) { }
public void Validate(ServiceEndpoint serviceEndpoint) { }
}
сообщение в spector добавляет куки, когда запрос отправляется на сервер в методе BeforeSendRequest
и извлекает файлы cookie, которые должны быть обновлены в методе AfterReceiveReply
. Обратите внимание, что correlationState
возвращаемого BeforeSendRequest
используются для получения Ури в AfterReceiveReply
:
public class CookieMessageInspector : IClientMessageInspector
{
private CookieContainer cookieCont;
public CookieMessageInspector(CookieContainer cookieCont)
{
this.cookieCont = cookieCont;
}
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply,
object correlationState)
{
object obj;
if (reply.Properties.TryGetValue(HttpResponseMessageProperty.Name, out obj))
{
HttpResponseMessageProperty httpResponseMsg = obj as HttpResponseMessageProperty;
if (!string.IsNullOrEmpty(httpResponseMsg.Headers["Set-Cookie"]))
{
cookieCont.SetCookies((Uri)correlationState, httpResponseMsg.Headers["Set-Cookie"]);
}
}
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,
System.ServiceModel.IClientChannel channel)
{
object obj;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out obj))
{
HttpRequestMessageProperty httpRequestMsg = obj as HttpRequestMessageProperty;
SetRequestCookies(channel, httpRequestMsg);
}
else
{
var httpRequestMsg = new HttpRequestMessageProperty();
SetRequestCookies(channel, httpRequestMsg);
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMsg);
}
return channel.RemoteAddress.Uri;
}
private void SetRequestCookies(System.ServiceModel.IClientChannel channel, HttpRequestMessageProperty httpRequestMessage)
{
httpRequestMessage.Headers["Cookie"] = cookieCont.GetCookieHeader(channel.RemoteAddress.Uri);
}
}
@marc_s: даже для службы ASMX, он должен использовать "Add Service Reference". –