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.
Asked
Active
Viewed 4,507 times
1
-
Geez these are all over the place. Are you sure you haven't looked? – cgatian Dec 12 '13 at 00:26
-
Something like this: http://stackoverflow.com/a/7929084/402022 – Theraot Dec 12 '13 at 13:40
-
1@cgatian Yes i have looked.. quite a bit and there seems to be a lot of confusion. – billy jean Dec 12 '13 at 14:47
-
@theraot well there is no specific definition of custom headers in that request. But the form parameters are there thanks! – billy jean Dec 12 '13 at 14:48
1 Answers
6
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();
}

Darrel Miller
- 139,164
- 32
- 194
- 243
-
Thanks for this.. Helps with the form properties but i also need to add custom headers. – billy jean Dec 12 '13 at 14:45
-
1@billyjean That's just an xunit test attribute. It makes it easy for me to run snippets of code. http://xunit.codeplex.com/ – Darrel Miller Dec 12 '13 at 22:43