Ralph Flotner
Ralph Flotner

Reputation: 11

RestSharp AddHeader not working

I am building a simple REST/Json windows client using C# and RestSharp 105.2.3. Everything is working beautifully but the additional HTTP header I am specifying does not seem to being added according to the Wireshark trace. Am I missing something or is there an underlying HTTP method I should use?

The code is straightforward as outlined below and I cannot see the RequestId header in the trace:

    var client = new RestClient("http://example.com");
    client.Authenticator = new HttpBasicAuthenticator("username", password");

    var requestParams = new RequestItem
    { Parameter1 = "test1", Parameter2 = "test2" };

    var request = new RestRequest("/sample/", Method.POST);
    request.AddHeader("RequestId", "value");

    request.RequestFormat = DataFormat.Json;
    request.Parameters.Clear();
    var requestParamsJson = request.JsonSerializer.Serialize(requestParams);
    request.AddParameter("application/json; charset=utf-8", requestParamsJson, ParameterType.RequestBody);
    IRestResponse<ResponseItem> response = client.Execute<ResponseItem>(request);

Upvotes: 1

Views: 5630

Answers (1)

user47589
user47589

Reputation:

You need to remove the request.Parameters.Clear(); call. Internally, RestSharp adds headers to the Parameters collection, which you're clearing. So removing the call, or moving it above where you add the header, will fix the issue.

Upvotes: 3

Related Questions