Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from RestSharp response headers

I'm hoping someone can help with an issue I'm having with RestSharp. It's all working; I'm getting my reply using the following code:

var client = new RestClient("http://mybaseuri.com");
var request = new RestRequest("service/{id}", Method.GET);
request.AddUrlSegment("id", id);
    
// execute the request
IRestResponse response = client.Execute(request);

I'd like to get a value from the response headers along the lines of:

string userId = response.Headers["userId"]

I can't find any examples online, can anyone help get a value from the response.Headers object which is of type IList<parameter>?

I'm not looking to iterate the entire collection, just extract a single value by name.

like image 721
user3580862 Avatar asked Apr 28 '14 10:04

user3580862


People also ask

How do I get the response header in RestSharp?

Type: HttpHeader Using LINQ: string userId = response. Headers . Where(x => x.Name == "userId") .

How do I request a RestSharp body?

The request body is a type of parameter. To add one, you can do one of these... req. AddBody(body); req.

Does RestSharp use HttpClient?

Since RestSharp uses the HttpClient, we should consider similar issues regarding the RestClient instantiation.


3 Answers

As I was wondering myself how to do the same, I find out the following solution with the help of this MSDN article about IList<T>:

string userId = response.Headers.ToList()
    .Find(x => x.Name == "userId")
    .Value.ToString();

I need to confess I'm fond of playing in Visual Studio with Immediate Window or Quick Watch to dig a bit and know what kind of element Type I'm dealing with:

response.Headers[0]

{userId=1024}

Name: "userId"

Type: HttpHeader

Value: "1024"

like image 74
Guillaume Raymond Avatar answered Oct 12 '22 12:10

Guillaume Raymond


Using LINQ:

string userId = response.Headers
    .Where(x => x.Name == "userId")
    .Select(x => x.Value)
    .FirstOrDefault();

This requires no knowledge of the index of the element, and deals with the scenario where the header does not exist.

like image 37
kadj Avatar answered Oct 12 '22 12:10

kadj


It's not difficult with Linq:

if( response.Headers.Any(t=>t.Headers == "Location"))
{
    string location = 
    response.Headers.FirstOrDefault(t=>t.Headers == "Location").Value.ToString();
}
like image 4
khablander Avatar answered Oct 12 '22 11:10

khablander