如何使用OperationContract从POST请求中捕获响应头?

时间:2016-03-16 10:29:36

标签: c# .net wcf rest datacontractserializer

我有以下WCF包装器来调用REST服务:

[DataContract]
public class InterestingResponse : IExtensibleDataObject
{
    [MessageHeader(Name="x-interesting-id")]
    public string InterestingId { get; set; }

    public ExtensionDataObject ExtensionData { get; set; }
}

[ServiceContract()]
public interface IManagement
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = @"somePathHere")]
    InterestingResponse DoInteresting();
}

请求正在发送到服务并成功完成。 HTTP响应具有空主体和x-interesting-id标头。我希望客户端代码返回InterestingResponse的实例,其中InterestingId被设置为响应中的x-interesting-id值。

一旦IManagement.DoInteresting()在客户端上返回,就会返回空引用,因为响应是空的,没有任何反序列化,我猜。

如何返回一个对象,并将标题值反序列化为对象成员?

1 个答案:

答案 0 :(得分:0)

System.ServiceModel.Channels.Message用作here。将方法声明更改为:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = @"somePathHere")]
Message DoInteresting();

然后一旦invokation完成,Message对象将包含带HTTP标头的HTTP响应:

var invokationResult = service.DoInteresting();
var properties = message.Properties;
var httpResponse = 
    (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name];
var responseHeaders = httpResponse.Headers;
var interestingHeader = reponseHeaders["x-interesting-id"];