I am trying to post to a .net controller using HttpClient, but the controller is never being hit....
Here is how I am trying to post:
NameValueCollection data = new NameValueCollection();
data.Add("someField", "someValue");
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync(url,
new FormUrlEncodedContent(data.Cast<string>()
.SelectMany(key => data.GetValues(key), (key, value) => new { key, value })
.ToDictionary(p => p.key, p => p.value))
);
}
And then my controller:
[HttpPost("MyController")]
public void MyControllerMethod(string someField)
{
// never being hit....
}
I can change it slightly and the method gets hit.... But in the following scenario, someField is null and it shouldn't be:
NameValueCollection data = new NameValueCollection();
data.Add("someField", "someValue");
var dictionary = data.Cast<string>()
.SelectMany(key => data.GetValues(key), (key, value) => new { key, value })
.ToDictionary(p => p.key, p => p.value);
var json = JsonConvert.SerializeObject(dictionary);
StringContent stringContect = new StringContent(json);
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync(url, stringContect);
}
But like I said, in that scenario, the param someField isn't mapping the way I expect it to and is showing as NULL instead of "someValue"....
Any ideas?
Thanks!
FormUrlEncodedContentwants anIEnumerable<Keypair<string,string>>. You're using anNameValueCollectionwhich supports duplicate keys, but your.ToDictionarywould break if there were any. IMHO If you don't need to support multiple keys with the same name, just use aDictionary<string,string>in the first place.