c# - 从请求上下文中添加和检索数据

标签 c# wcf asp.net-mvc-3

我正在尝试将 api key 附加到 OperationContext 传出消息 header ,如下所示:

    public static void AddApikeyToHeader(string apikey, IContextChannel channel, string address)
    {
        using (OperationContextScope scope = new OperationContextScope(channel))
        {
            MessageHeader header = MessageHeader.CreateHeader("apikey", address, apikey);
            OperationContext.Current.OutgoingMessageHeaders.Add(header);

        }
    }

但是我不知道如何在服务器端检索 header 。我正在使用服务授权管理器,我获得了当前的操作上下文并尝试像这样检索 header :

    public string GetApiKey(OperationContext operationContext)
    {
        var request = operationContext.RequestContext.RequestMessage;

        var prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

        return prop.Headers["apikey"];
    }

但那里没有附加 apikey header 。此外,在调试时,当我检查 operationContext 时,我似乎无法在任何地方看到我的 apikey header 。谁能看出我哪里出错了?

最佳答案

您可以通过这种方式添加自定义 header :

using (ChannelFactory<IMyServiceChannel> factory = 
       new ChannelFactory<IMyServiceChannel>(new NetTcpBinding()))
      {
       using (IMyServiceChannel proxy = factory.CreateChannel(...))
       {
          using ( OperationContextScope scope = new OperationContextScope(proxy) )
          {
             Guid apiKey = Guid.NewGuid();
             MessageHeader<Guid> mhg = new MessageHeader<Guid>(apiKey);
             MessageHeader untyped = mhg.GetUntypedHeader("apiKey", "ns");
             OperationContext.Current.OutgoingMessageHeaders.Add(untyped);

             proxy.DoOperation(...);
          }
       }                    
    }

和服务端,你可以得到这样的标题:

Guid apiKey = 
OperationContext.Current.IncomingMessageHeaders.GetHeader<Guid>("apiKey", "ns");

关于c# - 从请求上下文中添加和检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7670666/

相关文章:

c# - 在流上生成 XOR 校验和的简单方法?

wcf - 处理 Azure 暂存疯狂 URL

c# - 未触发 WCF 客户端关闭事件

n 层应用程序中的 WCF 服务层 : performance considerations

jquery - 使用 javascript 调用操作并导致回发

jquery - MVC 3 AJAX 和 [ValidateAntiForgeryToken]

c# - 用循环填充数组

c# - System.Net.Mail.SmtpException : Insufficient system storage. 服务器响应为: 4. 3.1 系统资源不足

asp.net-mvc-3 - MVC3 未终止的字符串常量语法错误

c# - 是否可以在 Serilog.Exceptions 中禁用基于反射的解构器?