【问题标题】:How do I obtain a response header value when making a REST call via WCF?通过 WCF 进行 REST 调用时如何获取响应标头值?
【发布时间】:2015-04-16 15:09:33
【问题描述】:

我的代码使用 WCF 使用第三方 REST 服务。服务接口声明如下:

[ServiceContract(Namespace = "SomeNamespace",
     ConfigurationName = "SomeName")]
public interface ICoolService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = @"whatever")]
    void CoolMethod(InputContainer input);
}

其中InputContainer 被声明为DataContract

[DataContract(Namespace = "whatever")]
public class InputContainer : IExtensibleDataObject
{
    //[DataMember]s inside
}

我的代码实例化使用WebChannelFactory 实例化一个“通道对象”,然后通过“通道对象”调用服务

ServiceEndpoint endpoint = ...craft endpoint;     
var factory = new WebChannelFactory<IServiceManagement>( endpoint );
var service = factory.CreateChannel();
service.CoolMethod( new InputContainer() );

而且效果很好。

现在问题...该服务的文档说该服务返回带有x-some-cool-header 和空正文的响应。

如何获取该响应标头的值(最好作为返回值CoolMethod())?

【问题讨论】:

  • 您的意思是如何在响应中添加标题?您使用什么客户端来调用服务?您需要发布代码的客户端部分。你指的是什么文档?
  • @JamesRalston 我试图澄清我的设置。我的代码使用了第三方服务。

标签: c# .net web-services wcf rest


【解决方案1】:

最简单的方法是更改​​接口声明,使方法返回System.ServiceModel.Channels.Message

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = @"whatever")]
Message CoolMethod(InputContainer input);

然后,一旦方法调用完成,您将获得一个 Message 对象,其中包含带有标头的 HTTP 响应:

var invokationResult = service.CoolMethod( new InputContainer() );
var properties = message.Properties;
var httpResponse = 
    (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name];
var responseHeaders = httpResponse.Headers;
var coolHeader = reponseHeaders["x-some-cool-header"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 2011-09-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多