【问题标题】:How to send and retrieve custom header information for REST WCF Service如何发送和检索 REST WCF 服务的自定义标头信息
【发布时间】:2019-03-08 12:32:50
【问题描述】:

我正在努力在我的解决方案中设置基础架构以发送和检索 REST WCF 服务的自定义标头。基本上,我们需要将用户 ID、密码、令牌值从客户端发送到服务,如果提供的值有效,则操作将继续执行,否则抛出异常。

我们已经有几个类继承自 IDispatchMessageInspector、IClientMessageInspector、IEndPointBehaviour、MessageHeader 等接口,这对于带有肥皂请求的 WCF 来说工作得很好。我尝试将这些类用于我的新 REST WCF 服务,但由于 MessageHeader 派生类仅支持 Soap,因此无法正常工作。

我也尝试过使用 WebOperationContext,但没有运气:(

请提供解决方案以及示例项目以解决此问题。

非常感谢!

【问题讨论】:

    标签: rest wcf c#-4.0


    【解决方案1】:

    在您的情况下,询问 ASPNET 管道可能更容易

    如果您将以下内容添加到您的 WCF 服务以允许它连接到 ASPNET 管道

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    然后您现在可以简单地使用 HttpContext 对象并像从普通 aspnet 应用程序中一样获取标头,例如

    System.Web.HttpContext.Current.Request.Headers["CustomHeader"]
    

    【讨论】:

      【解决方案2】:

      如果你想在 wcf rest 服务中添加 http header,你应该使用 HttpRequestMessageProperty,它有一个 Headers 属性,你可以通过它的 Headers 属性设置 http Header

       using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
                  {
                      HttpRequestMessageProperty property;
                           // if OutgoingMessageProperties already has HttpRequestMessageProperty, use the existing one , or  initialize a new one and 
                       set   OutgoingMessageProperties's HttpRequestMessageProperty.Name key's value to the initialized  HttpRequestMessageProperty so that the HttpRequestMessageProperty  will work 
                      if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name)){
                          property = OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                      }
                      else
                      {
                          property = new HttpRequestMessageProperty();
                          OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = property;
                      }
                // add headers to  HttpRequestMessageProperty, it will become the http header of the reuqest
                      property.Headers.Add(System.Net.HttpRequestHeader.Authorization, "myAuthorization");
                      string re = client.HelloWorld();
                  }
      

      关于获取 Header ,只需使用 WebOperationContext.Current.Headers。

      WebOperationContext.Current.IncomingRequest.Headers["MyCustomHttpHeader"]
      

      请参考http://kenneththorman.blogspot.com/2011/02/wcf-rest-client-using-custom-http.html

      【讨论】:

        猜你喜欢
        • 2016-06-22
        • 1970-01-01
        • 1970-01-01
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多