Reputation: 12599
One of the websites I'm sending a Post request has a single ampersand (&) at the end of the Post Data thats sent with the Post request.
How to I append an & to the end of the Post Data when using HttpContent?
Here's an example of the code:
List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("user", userid));
postData.Add(new KeyValuePair<string, string>("password", password));
HttpContent content = new FormUrlEncodedContent(postData);
HttpResponseMessage responseMessage = await client.PostAsync("https://www.site.com/login", content);
The Post Data sent needs to look like:
username=324234&password=12345&
It's odd there is an & at the end of the request, but without it the request fails.
Please note, this is NOT an & at the end of the 'password' field. If I was to add that, it would encode the &. The & is sent with every request regardless of the password used.
Any ideas?
Upvotes: 1
Views: 530
Reputation: 292615
FormUrlEncodedContent
doesn't support this, but you can always add the final '&' yourself and send the result as a StringContent
:
HttpContent content = await new FormUrlEncodedContent(postData)
.WithFinalAmpersandAsync();
...
static class HttpContentExtensions
{
public static async Task<HttpContent> WithFinalAmpersandAsync(
this FormUrlEncodedContent formUrlEncodedContent)
{
string content = await formUrlEncodedContent.ReadAsStringAsync();
return new StringContent(content + "&");
}
}
Upvotes: 1