在我的客户端中,在调用服务之前,我在发送到 wcf 服务之前向请求添加了一个 token (guid)。
AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
在此方法中,我想验证请求 header 是否具有在客户端中添加的 token (guid)。所以我在这里使用了这部分代码:
Guid securityTokenId = request.Headers.GetHeader<Guid>("Token", "System");
如果在任何情况下在 header 中找不到此“ token ”,我的 securityTokenId
是否会返回 Guid.Empty
?或者它返回什么?
最佳答案
如果没有具有该名称/命名空间的 header ,您将在调用 GetHeader 时收到异常 (MessageHeaderException
)。如果不想处理异常,可以先查看这样的 header 是否存在(使用 FindHeader 方法),然后如果返回非负值,则获取对应的 header。
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();
}
}
关于c# - 我已经实现了 AfterReceiveRequest 方法(来自 IDispatchMessageInspector),并且想要验证请求是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8854137/