使用WCF OperationContext通过Channel传递标头值

Dom*_*ton 7 c# wcf

我有一个WCF服务,需要将应用程序ID参数传递给每个服务调用.目前我暴露的方法需要一个参数.我想尝试将此信息推送到Channel标头中.我的WCF使用Net.tcp托管.这是我的客户端代理代码:

public class CustomerClient : ClientBase<ICustomerBrowser>, ICustomerBrowser
{
  public Customer Get(string ApplicationID, string CustomerId)
  {
    try
    {
        using (OperationContextScope _scope = new OperationContextScope(this.InnerChannel))
        {
            MessageHeader _header = MessageHeader.CreateHeader("AppID", string.Empty, ApplicationId);
            OperationContext.Current.OutgoingMessageHeaders.Add(_header);
            return Channel.Get(ApplicationId, CustomerId);
            // return Channel.Get(CustomerId);
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

(注释掉的行是我想要继续使用的).

服务器代码:

var _context = WebOperationContext.Current;
var h = _context.IncomingRequest.Headers;
Run Code Online (Sandbox Code Playgroud)

在_context对象中有私有方法包含我的标题,但在_context.IncomingRequest.Headers中公开我得到这个:

public class CustomerClient : ClientBase<ICustomerBrowser>, ICustomerBrowser
{
  public Customer Get(string ApplicationID, string CustomerId)
  {
    try
    {
        using (OperationContextScope _scope = new OperationContextScope(this.InnerChannel))
        {
            MessageHeader _header = MessageHeader.CreateHeader("AppID", string.Empty, ApplicationId);
            OperationContext.Current.OutgoingMessageHeaders.Add(_header);
            return Channel.Get(ApplicationId, CustomerId);
            // return Channel.Get(CustomerId);
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,我受苦是因为我不是在HTTP上托管?有没有办法欺骗服务器通过添加一些伪HTTP标头让我访问这些标头?或者我可以通过反思得到私人会员?

ren*_*ene 5

您使用的错误实例OperationContext

WebOperationContext专业为通过HTTP传输的消息。它期望其标头具有指定名称。如果是WebOperationContextMessageHeaders词典,则需要一个名为的键httpRequest,该键在您的方案中未提供。

在使用标准OperationContext客户端时,应该在同一服务器端:

var _context = OperationContext.Current;
var headers = _context.IncomingMessageHeaders; 
foreach (MessageHeaderInfo h in headers)
{
     if (h.Name == "AppID") {
        Debug.WriteLine(h.ToString());
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 尝试`_context.IncomingMessageHeaders.GetHeader &lt;T&gt;(...)`方法 (5认同)