wcf - 如何将http header 添加到WCF channel 中

标签 wcf wcf-binding wcf-security

我有调用 WCF 服务的 MVC 客户端。 MVC 客户端需要在 httprequest 中传递一个自定义 header 。 MVC 客户端也使用 Unity 进行 DI。

我已经浏览过SO POST和其他链接,但他们都建议使用消息检查器和自定义行为(这可能是正确的方法),但我正在寻找快速而肮脏的方法,因为这将是临时解决方案。

    // Unity type Registration
    public static void RegisterTypes(IUnityContainer container)
    {
       container.RegisterType<IDocumentManagementChannel>(new PerRequestLifetimeManager(),
            new InjectionFactory(f=> CreateDocumentManagementChannel()));
    }

    private static IDocumentManagementChannel CreateDocumentManagementChannel()
    {

        var factory = new ChannelFactory<IDocumentManagementChannel>("BasicHttpEndPoint");
        var channel =  factory.CreateChannel();

        // How do i add HttpHeaders into channel here?

        return channel
    }

在上面的代码中,创建 channel 后如何添加自定义 header ?

最佳答案

1-下面的代码应该从 MVC 发送 SOAP header

            string userName = Thread.CurrentPrincipal.Identity.Name;
            MessageHeader<string> header = new MessageHeader<string>(userName);               

            OperationContext.Current.OutgoingMessageHeaders.Add(
                                      header.GetUntypedHeader("String", "System"));

2- 此代码应该在 WCF 上读取

  string loginName = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("String", "System");

3- 至于 channel ,我建议您创建自定义 System.ServiceModel.ClientBase,如下所示:

public abstract class UserClientBase<T> : ClientBase<T> where T : class
    {
        public UserClientBase()
        {
            string userName = Thread.CurrentPrincipal.Identity.Name;
            MessageHeader<string> header = new MessageHeader<string>(userName);

            OperationContext.Current.OutgoingMessageHeaders.Add(
                                      header.GetUntypedHeader("String", "System"));
        }
    }

4- 创建一个继承自 UserClientBase 的自定义客户端类,并在内部使用基本 channel 来调用您的 IxxService,即此处的 T。

关于wcf - 如何将http header 添加到WCF channel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44312572/

相关文章:

c# - 未找到 WCF 服务端点

wcf - 连接被拒绝 - 工作中的 nettcp WCF 服务 - 客户端通过 VPN 连接

wcf - 带有双向 SSL 安全证书的 Silverlight WCF

c# - 在保护 WCF 服务方面需要帮助

c# - 我如何使用WCF服务而不是套接字客户端服务器应用程序?

c# - netpeertcpbinding 是否支持请求/回复

.net - 如何将 session 数据加密到 token 中以授权后续 Web 服务调用?

iis-7.5 - 如何保护托管在 IIS 7.5 上的面向公众的 WCF 服务?

wcf - WCF 中的实例停用是什么?

wcf - 托管服务引擎 (MSE) 路线图