将值传递给WCF中的BeforeSendRequest

时间:2014-06-27 06:15:05

标签: c# .net web-services wcf iclientmessageinspector

我想将附加值(GUID,每个请求不同)传递给WCF BeforeSendRequest接口中的IClientMessageInspector。此值不包含在请求对象中。如何将此值传递给BeforeSendRequest方法?

1 个答案:

答案 0 :(得分:1)

public class WcfMessageInterceptor : IDispatchMessageInspector, IClientMessageInspector
{
    [ThreadStatic]
    private static string service1GUID;

    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        service1GUID = request.Headers.GetHeader("service1-guid-header", "s");
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        var serviceName="";
        if (channel != null && channel.RemoteAddress != null)
        {
            var tmp = request.Headers.Action.Substring(0, request.Headers.Action.LastIndexOf('/'));
            serviceName = tmp.Substring(tmp.LastIndexOf('/') + 1);
        }
        var methodName = request.Headers != null
                                ? request.Headers.Action.Substring(request.Headers.Action.LastIndexOf('/') + 1)
                                : "Action";
        //check if the called service is the right one
        if(serviceName=="Service2"){
            var typedHeader = new MessageHeader(service1GUID);
            var untypedHeader = typedHeader.GetUntypedHeader("service1-guid-in-service2-header", "s");
            request.Headers.Add(untypedHeader);
        }
    }
}