wcf - 无法读取 WCF 服务中的 header

标签 wcf http-headers

我正在尝试添加自定义安全功能,其中客户端将 token 添加到 Silverlight 客户端进行的每个服务调用,然后服务可以访问此 token 以控制应用程序安全系统。我试图通过实现 IClientMessageInspector 接口(interface)并将其链接到我生成的服务客户端来做到这一点。我没有使用 Visual Studio 生成的代理,而是我自己的由 ChannelFactory 创建的客户端。我设法在网上找到了几种解决方案,它们似乎都使用了两种基本方法之一。首先通过向呈现给 IClientMessageInspector.BeforeSendRequest 的 Message 的 headers 集合添加 header ,其次通过使用 HttpRequestMessageProperty 将信息作为属性添加到呈现给 IClientMessageInspector.BeforeSendRequest 的 Message。我一直在尝试这两种方法都没有成功。看来这两种技术都成功地将数据添加到请求中,但我无法在服务器上访问任何一个。我要补充一点,这对我来说是一个非常新的领域,我很可能因为缺乏经验而错过了互联网上的答案。

生成我的客户端的代码是:

    private ISecurityAdministrationContract CreateChannel()
    {
        if (factory == null)
        {
            lock (this)
            {
                // Create a custom binding that uses HTTP and binary encoding.
                var elements = new List<BindingElement>();
                elements.Add(new BinaryMessageEncodingBindingElement());
                elements.Add(new HttpTransportBindingElement());
                var binding = new CustomBinding(elements);

                // Create a channel factory for the service endpoint configured with the custom binding.
                factory = new ChannelFactory<ISecurityAdministrationContract>(binding, new EndpointAddress(SecurityAdminServiceAddress));

                //Add my IClientMessageInspector
                factory.Endpoint.Behaviors.Add(new ClientSecurityInterceptor());
            }                
        }
        ISecurityAdministrationContract client = factory.CreateChannel();
        return client;
    }
        }
        ISecurityAdministrationContract client = factory.CreateChannel();
        return client;
    }

将我的 header 添加到请求的代码是:
    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
    {
        //Method 1
        MessageHeader header = MessageHeader.CreateHeader("MyFirstAuthentication", "ns", "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEEE");
        request.Headers.Add(header);

        //Method 2
        HttpRequestMessageProperty httpRequestMessage;
        httpRequestMessage = new HttpRequestMessageProperty();
        httpRequestMessage.Headers["MySecondAuthentication"] = "11111111-2222-3333-4444-5555555555555";
        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);

        return null;
    }

上面的代码实现了这两种技术。

fiddler 捕获的服务调用是:(NB http 替换为 ht_tp 因为该站点不允许我发布 hyoerlinks)

POST ht_tp://127.0.0.1:6785/SecurityAdministrationRelayService.svc/ HTTP/1.1 Accept: / Referer: ht_tp://ipv4.fiddler:6785/ClientBin/Civica.Housing.xap Accept-Language: en-gb Content-Length: 400 Content-Type: application/soap+msbin1 MySecondAuthentication: 11111111-2222-3333-4444-5555555555555 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB5; InfoPath.2; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727) Host: 127.0.0.1:6785 Connection: Keep-Alive Pragma: no-cache

V_ s _a_V_D ���Ahttp://tempuri.org/ISecurityAdministrationContract/CreateAdvocateD�ߔ_�9�HJ��9��-��D,D*�@MyFirstAuthentication_ns�%AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEEED _���@http://ipv4.fiddler:6785/SecurityAdministrationRelayService.svc/V@_CreateAdvocate_http://tempuri.org/@ advocateVO�{"Id":0,"UserId":4,"AdvocateForId":8,"ValidFrom":"/Date(1291127869690+0000)/","ValidTo":null}__



这似乎包含两种技术的 token 信息。

当我尝试提取此信息时,问题出现在服务器上。我已经实现了一个 IOperationInvoker 并试图在 IncomingMessageHeaders 中找到标题但没有任何成功。我也在 IncomingMessageProperties 中进行了搜索,但我看不到我添加的任何标题详细信息。
这是我在 IOperationInvoker 中使用的代码:
    public object Invoke(object instance, object[] inputs, out object[] outputs)
    {
        PreInvoke(instance, inputs);
        object returnedValue = null;
        object[] outputparams = new object[] { };
        Exception exception = null;
        try
        {
            returnedValue = originalInvoker.Invoke(instance, inputs, out outputparams);
            outputs = outputparams;
            return returnedValue;
        }
        catch (Exception e)
        {
            exception = e; throw;
        }
        finally
        {
            PostInvoke(instance, returnedValue, outputparams, exception);
        }
    }


    protected virtual void PreInvoke(object instance, object[] inputs)
    {
        //Look for header directly
        int index = System.ServiceModel.OperationContext.Current.IncomingMessageHeaders.FindHeader("MyFirstAuthentication", "ns");

        //Search via enumerator
        foreach (var header in System.ServiceModel.OperationContext.Current.IncomingMessageHeaders)
        {
        }

    }

FindHeader 返回 -1 而枚举器找到 5 个 header ,即; “Action”、“MessageID”、“ReplyTo”、“VsDebuggerCausalityData”和“To”。

OperationContext.Current.IncomingMessageProperties 集合包含 4 个条目,即:“Via”、“Security”、“Encoder”和“System.ServiceModel.Channels.RemoteEndpointMessageProperty”

事实上,如果我在客户端中注释掉将 IClientMessageInspector 添加到 ClienChannel 的行,那么 fiddler 报告的 http 会通过省略添加的详细信息而发生变化,但传入消息的 header 和属性集合不会改变。

任何关于我如何访问此信息的想法,或者为什么它没有作为 IncomingMessage 的一部分呈现,我们将非常感激地收到。

最佳答案

我已经回答了我自己的问题。上述任何代码都没有错,只需要链接到正确的位置即可。在我的完整解决方案中,我从 Silverlight 客户端调用服务,然后调用第二个服务。令人尴尬的是,我已将 IOperationInvoker 链接到第二个服务 (doh)。当我将它链接到中间服务时,标题按预期可用。

读取值的代码是:

            int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("MyFirstAuthentication", "ns");
            if (index >= 0)
            {
                string value = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(index);
            }

关于wcf - 无法读取 WCF 服务中的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4315063/

相关文章:

ios - 如何在 UIWebView 请求中添加自定义 HTTP header ,我的 UIWebView 是基于 Cordova 项目的?

c# - 为什么在 WCF 中使用 LocalChannel 时执行序列化?

c# - 实体到 WCF 数据协定

c# - SOAP 和 REST 网络服务有什么区别? SOAP 可以是 RESTful 吗?

php - X-Backside-Transport header 有什么作用?

c# - 内容处置文件名不适用于 IE

php - 重定向功能 Php

wcf - 远程服务器返回错误: (413) Request Entity Too Large

.net - WCF UriTemplate 不会匹配带有斜杠(/)的单个字符串参数

xml - 如何向 Facebook 提交错误报告?