简体   繁体   中英

ServiceStack JsonServiceClient Response Header

I'm new to ServiceStack so please forgive my ignorance...

How can I the JsonServiceClient to give my my DataContract response object and also allow me to get the response header with only a single request?

I've figured out how to return a populated DataContract Response object like this:

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});

I've also figured out how to get a response header item from the HttpWebResponse overload like this (see below) which requires the slight modification of commenting out the request data contract interface as shown here: 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];

But again, how can I do both at once?

I did figure out how to do this with the .PostJsonToUrl() extension method but my question is how can I do this with the JsonServiceClient . If anyone is curious here's how I did it with the .PostJsonToUrl() extension method:

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>();

Here are my DataContract Classes

[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; }
}

All ServiceStack's .NET Clients include both a ResponseFilter and static GlobalResponseFilter property you can use to inspect the HTTP Response before the response is deserialized, eg:

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

var response = client.Post(request);

Where response will contain the deserialized Response body and myHeader will be populated with the value of X-MyHeader HTTP Header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM