billy jean
billy jean

Reputation: 1419

Posting with C# httpclient with formencoded paramaters and headers

i am looking for a simple example using .net HttpClient to POST parameters and add headers. This is super easy in RestSharp but so far i cannot see a clear way how to do this with the HttpClient.

Upvotes: 1

Views: 4839

Answers (1)

Darrel Miller
Darrel Miller

Reputation: 142094

If you want to modify request headers for every request then the easiest way to do it is by setting the DefaultRequestHeaders properties. However, if you really want to change the request headers just for a particular request then you need to use the SendAsync method and pass it a HttpRequestMessage.

[Fact]
public async Task Post_a_form_and_change_some_headers()
{

    var client = new HttpClient() { BaseAddress = _BaseAddress };

    var values = new Dictionary<string, string>()
    {
        {"Id", "6"},
        {"Name", "Skis"},
        {"Price", "100"},
        {"Category", "Sports"}
    };
    var content = new FormUrlEncodedContent(values);

    var request = new HttpRequestMessage()
    {
        RequestUri = new Uri("devnull",UriKind.Relative),
        Method = HttpMethod.Post,
        Content = content
    };
    request.Headers.ExpectContinue = false;
    request.Headers.Add("custom-header","a header value");

    var response = await client.SendAsync(request);

    response.EnsureSuccessStatusCode();
}

Upvotes: 7

Related Questions