ServiceStack JsonServiceClient响应标头

时间:2018-04-07 19:12:10

标签: c# rest servicestack

我是ServiceStack的新手,所以请原谅我的无知......

我如何JsonServiceClient提供我的DataContract响应对象,并允许我只用一个请求获取响应标头?

我已经想出如何返回一个填充的DataContract Response对象,如下所示:

var field1 = "aaa";
var field2 = "bbb";

var client = new JsonServiceClient("https://api.server.com/api");
Response1 response1 = client.Post(new Request1() { Field1= field1, Field2= field2});

我还想出了如何从HttpWebResponse重载中获取响应头项目(如下所示),这需要稍微修改注释掉请求数据合约接口,如下所示: class Request1 //: IReturn<Response1>

var field1 = "aaa";
var field2 = "bbb";

var client = new JsonServiceClient("https://api.server.com/api");
HttpWebResponse response1 = client.Post(new Request1() { Field1= field1, Field2= field2});
var value = response1.Headers.GetValues("Item")[0];

但是,我怎么能同时做到这两件事呢?

我确实知道如何使用.PostJsonToUrl()扩展方法执行此操作,但我的问题是如何使用JsonServiceClient执行此操作。如果有人对此感到好奇,我会使用.PostJsonToUrl()扩展方法:

var url = "https://api.server.com/api/method";
string value = null;
Response1 response1 = url.PostJsonToUrl(new Request1() { Field1= field1, Field2= field2},
    null, httpResponse =>
    {
        value = httpResponse.Headers.GetValues("Item")[0];
    }).FromJson<Request1>();

以下是我的DataContract类

[Route("/method")]
[DataContract]
class Request1 : IReturn<Response1>
{
    [DataMember(Name = "field1")]
    public string Field1 { get; set; }
    [DataMember(Name = "field2")]
    public string Field2 { get; set; }
}

[DataContract]
class Response1
{
    [DataMember(Name = "field1")]
    public long Field1 { get; set; }

    [DataMember(Name = "field2")]
    public string Field2 { get; set; }

    [DataMember(Name = "field3")]
    public string Field3 { get; set; }
}

1 个答案:

答案 0 :(得分:1)

所有ServiceStack's .NET Clients都包含ResponseFilter和静态GlobalResponseFilter属性,可用于在反序列化响应之前检查HTTP响应,例如:

string myHeader = null;
var client = new JsonServiceClient(baseUrl) {
    ResponseFilter = res => myHeader = res.Headers["X-MyHeader"],
};

var response = client.Post(request);

response将包含反序列化的响应正文,myHeader将填充X-MyHeader HTTP标头的值。