Dev*_*Joe 3 c# asp.net httpclient
我已经搜索了所有都无济于事,仍然没有解决方案。我正在尝试使用 asp.net 控制台应用程序和 httpclient 从第三方服务获取身份验证令牌。一切都在 Postman 中工作,但在 c# 中复制相同返回"{\"error\":\"unsupported_grant_type\"}"
这是我的代码
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");
}
}
Run Code Online (Sandbox Code Playgroud)
感谢期待...抱歉,我已将 grant_type 更新为密码。它实际上不是grant_type,因为“密码”也不起作用。
问题似乎与这部分代码有关:
var multiform = new MultipartFormDataContent()
{
{new StringContent("password"), "grant_type" },
{new StringContent("adfadsasdfas"), "username" },
{new StringContent("asdfasdadf"), "password" },
};
Run Code Online (Sandbox Code Playgroud)
你应该改用这个:
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")
}
);
Run Code Online (Sandbox Code Playgroud)