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"];

Assert.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);

Authorization

For Bearer and Basic authorization use the Authorization method rather than setting the header yourself - see Authorization.

DefaultRequestHeaders is read only - default headers are set via the constructor (or AddRestClient()), and added to or overridden per request with the Headers method.

Updated: