我想通過c#訪問ASP.NET Web API。我編寫了API,並且能夠訪問它並使用Postman獲得有效的響應。當呈現username
,password
和grant_type = password
時,API返回access_token和refresh_token。unsupported_grant_type當PostAsJsonAync
下面是我用郵差當接收響應的屏幕截圖:
然而,當我嘗試使用下面的C#代碼:
var userToValidate = new UserToValidate
{
UserName = "[email protected]",
Password = "Abc123!",
grant_type = "password"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:4321");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("oauth/token", userToValidate).Result;
content = response.Content.ReadAsStringAsync().Result;
}
我得到一個錯誤... {"error":"unsupported_grant_type"}
我必須在C#方面做錯了什麼NGS。我錯過了什麼?
P.S.使用.Result
因爲調試async
代碼驅使我堅果
我在這個SO帖子中找到了解決方案。 http://stackoverflow.com/questions/29246908/c-sharp-unsupported-grant-type-when-calling-web-api。必須使用'application/x-www-form-urlencoded'而不是JSON。 – webworm
此外,您可以傳遞PostData作爲KeyValuePair而不是UserToValidate類'List> postData = new List >(); postData.Add(new KeyValuePair (「grant_type」,「password」)); postData.Add(new KeyValuePair (「username」,userName)); postData.Add(new KeyValuePair (「password」,password)); ' –
Paresh
@Paresh - 你可以發表一個答案,我會接受iy。這樣有多種選擇。謝謝。 – webworm