Hi Below is my current code:
var url = "https://localhost:44332/token";
var login = new Login()
{
username = "[email protected]",
password = "Password@1",
grant_type = "password"
};
using (var client = new HttpClient())
{
httpResponseMessage = await client.PostAsJsonAsync(url, login);
if (httpResponseMessage.IsSuccessStatusCode)
{
var token = httpResponseMessage.Content.ReadAsStringAsync();
}
}
My error is that 400: Bad Request, whenever i make the API call. If i use postman, its working, The following is what i put in POSTMAN body: "[email protected]&password=Password@1&grant_type=password"
Many Thanks in advance if anyone can correct me!
CodePudding user response:
It looks like you're trying to get hte token from OAuth 2.0 authentications server. You shouldn't be posting JSON - it expects the data as form. It returns a JSON object with access token storen in property access_token
- you probably will need to deserialize it as well.
using System.Net.Http.Json;
using System.Text.Json.Serialization;
var url = "https://localhost:44332/token";
var form = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username","[email protected]@1"},
{"password", "Password@1"},
};
using (var client = new HttpClient())
{
var response = await client.PostAsync(url, new FormUrlEncodedContent(form));
if (response.IsSuccessStatusCode)
{
var token = await response.Content.ReadFromJsonAsync<Token>();
var accessToken = token.AccessToken;
}
}
class Token
{
[JsonPropertyName("access_token")]
public string AccessToken { get; set; }
[JsonPropertyName("token_type")]
public string TokenType { get; set; }
[JsonPropertyName("expires_in")]
public int ExpiresIn { get; set; }
[JsonPropertyName("refresh_token")]
public string RefreshToken { get; set; }
}
CodePudding user response:
Do you pass these parameters by URL in postman? This form [email protected]&password=Password@1&grant_type=password
looks like you use URL past parameters in postman.
Usually, in POST requests we pass parameters in the request body, not the URL.
Besides, a recommendation is not directly a HttpClient instance. If you use .NET Framework and create the HttpClient instance directly, cannot release the socket resource even if you disposable the HttpClient object. If you use .NET Core, you can inject an HttpClient or IHttpClientFactory.
Refers: Use IHttpClientFactory to implement resilient HTTP requests