Headers
Default Headers
Default Headers are added to every request, by default RestClient has accept and content headers set for JSON.
You can add/override the default headers by providing a Dictionary<string,string> or Headers object to the constructor, the key is a string representing the header field for example “Accept”, and the value is a string representing the header field value for example “application/json”.
Example usage Dictionary<string, string>
:
dynamic client = new RestClient(
"https://jsonplaceholder.typicode.com",
new Dictionary<string, string> { { "Accept", "text/html" } });
Example usage using Headers
:
dynamic client = new RestClient(
"https://jsonplaceholder.typicode.com",
new Headers { { "Accept", "text/html" } } ));
//Or
dynamic client = new RestClient(
"https://jsonplaceholder.typicode.com",
new Headers (new { Accept = "text/html" });
Example usage reading Default Headers:
dynamic client = new RestClient("https://headers.jsontest.com/");
var acceptHeader = client.DefaultRequestHeaders["Accept"];
Asset.That(acceptHeader, Is.EqualTo("application/json"));
Per Request Headers
You can add/override the default headers per request using the Headers method, the Headers method takes one argument of Dictionary<string, string>
, Headers or an anonymous object, the key is a string representing the header field, and the value is a string representing the header field value.
Example usage anonymous object:
dynamic client = new RestClient("https://headers.jsontest.com/");
await client
.Headers(new { Accept = "text/html" })
.Users
.Get(1);
Example usage Dictionary<string, string>
:
dynamic client = new RestClient("https://headers.jsontest.com/");
await client
.Headers(new Dictionary<string, string> { { "Accept", "text/html" } })
.Users
.Get(1);
Example usage Headers
:
dynamic client = new RestClient("https://headers.jsontest.com/");
await client
.Headers(new Headers { { "Accept", "text/html" } })
.Users
.Get(1);
//Or
await client
.Headers(new Headers(new { Accept = "text/html" }))
.Users
.Get(1);
Breaking Change Since Version 3.1
Since version 3.1 the DefaultRequestHeaders Dictionary is readonly the only way to add DefaultHeaders is passing a Dictionary to the constructor. You can add/override the headers on a per request basis using the Headers method.
client.DefaultRequestHeaders.Add(“Accept”, “application/json”); //Not supported since version 3.1