如果沒有包含該名稱/名稱空間的標頭,則在調用GetHeader時會發生異常(MessageHeaderException
)。如果你不想處理異常,你可以先看看這個頭是否存在(使用FindHeader
方法),那麼如果它返回一個非負值,就得到相應的頭。
public class StackOverflow_8854137
{
[ServiceContract]
public interface ITest
{
[OperationContract]
string Echo(string text);
}
public class Service : ITest
{
public string Echo(string text)
{
return text;
}
}
class MyBehavior : IEndpointBehavior, IDispatchMessageInspector
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
public void Validate(ServiceEndpoint endpoint)
{
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
try
{
Guid tokenId = request.Headers.GetHeader<Guid>("Token", "System");
Console.WriteLine("Token: {0}", tokenId);
}
catch (Exception e)
{
Console.WriteLine("{0}: {1}", e.GetType().FullName, e.Message);
}
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
endpoint.Behaviors.Add(new MyBehavior());
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.Echo("No token"));
using (new OperationContextScope((IContextChannel)proxy))
{
OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("Token", "System", Guid.NewGuid()));
Console.WriteLine(proxy.Echo("With token"));
}
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
是否實施IDisptachMessageInspector和端點行爲的變化對所有類型,如HTTP,TCP或綁定了NamedPipes支持的? – user1086046 2012-01-16 15:40:33
卡洛斯,你可以請發佈web.config爲您的文章http://blogs.msdn.com/b/carlosfigueira/archive/2011/04/19/wcf-extensibility-message-inspectors.aspx 這是非常有益的。 – user1086046 2012-01-16 16:05:15
Re:第一個問題:消息檢查員工作不管綁定。第二,該文章中的代碼是自託管的,並且所有服務設置均以代碼完成。我實際上(個人)不喜歡使用web.config,你可以在http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/14/wcf-extensibility-servicehostfactory.aspx上看到更多關於它的信息。 。 – carlosfigueira 2012-01-17 03:50:53