I have searched all over SO all to no avail, still have no solution.
I'm trying to get auth token from an third party service using asp.net console app and httpclient.
Everything works in Postman but replicating same in c# returns "{\"error\":\"unsupported_grant_type\"}"
Here's my code
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var multiform = new MultipartFormDataContent()
{
{new StringContent("password"), "grant_type" },
{new StringContent("adfadsasdfas"), "username" },
{new StringContent("asdfasdadf"), "password" },
};
var response = Task.Run(() => httpClient.PostAsync("http://localhost:61216/token", multiform)).Result;
var message = Task.Run(() => response.Content.ReadAsStringAsync()).Result;
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException("Unable to post to cliams manager");
}
}
Thanks in anticipation... Sorry I have updated the grant_type to password. It's actually not the grant_type because "password" also didn't work.
The issue seems to be with this part of the code:
var multiform = new MultipartFormDataContent()
{
{new StringContent("password"), "grant_type" },
{new StringContent("adfadsasdfas"), "username" },
{new StringContent("asdfasdadf"), "password" },
};
You should be using this instead:
var content = new FormUrlEncodedContent(
new KeyValuePair<string, string>[] {
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", "asdfsad"),
new KeyValuePair<string, string>("password", "asdfaasdfa")
}
);