Postman Post call 截圖
您好以下是我當前的代碼:
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();
}
}
我的錯誤是 400:錯誤請求,每當我進行 API 呼叫時。如果我使用郵遞員,它的作業,以下是我在郵遞員正文中輸入的內容:“[email protected]&password=Password@1&grant_type=password”
非常感謝,如果有人可以糾正我!
uj5u.com熱心網友回復:
看起來您正試圖從 OAuth 2.0 身份驗證服務器獲取 hte 令牌。您不應該發布 JSON - 它期望資料作為表單。它回傳一個帶有存盤在屬性中的訪問令牌的 JSON 物件access_token——您可能還需要反序列化它。
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; }
}
uj5u.com熱心網友回復:
您是否在郵遞員中通過 URL 傳遞這些引數?此表單[email protected]&password=Password@1&grant_type=password看起來像您在郵遞員中使用 URL 過去引數。
通常,在 POST 請求中,我們在請求正文中傳遞引數,而不是 URL。
此外,推薦不直接是 HttpClient 實體。如果您使用.NET Framework 并直接創建 HttpClient 實體,即使您丟棄 HttpClient 物件也無法釋放套接字資源。如果使用 .NET Core,則可以注入 HttpClient 或 IHttpClientFactory。
參考:使用IHttpClientFactory實作彈性HTTP請求
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493147.html
