如何在C#WPF中使用HttpClient请求Web API OAuth令牌



我是WPF的新手,想通过HttpClient调用oauth令牌api来获取经过身份验证的令牌。我尝试了很多解决方案,但仍然得到了响应糟糕的请求(400(
我也和邮递员核实过,api运行良好
邮递员响应

尝试的解决方案:
(1(

var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = new FormUrlEncodedContent(param);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
request.Content.Headers.ContentType.CharSet = "UTF-8";
using (HttpResponseMessage response = await ApiHelper.apiClient.SendAsync(request))
{
Console.WriteLine("postRequest -> StatusCode -> " + response.StatusCode);
if (response.IsSuccessStatusCode)
{
//ComicModel comic = await response.Content.ReadAsAsync<ComicModel>();
var responseString = await response.Content.ReadAsStringAsync();
return response;
}
else
{
Console.WriteLine("postRequest -> exception -> " + response);
throw new Exception(response.ReasonPhrase);
}
}

(2(

using (var content = new FormUrlEncodedContent(param))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
using (HttpResponseMessage response = await ApiHelper.apiClient.PostAsync(url, content))
{
Console.WriteLine("postRequest -> StatusCode -> " + response.StatusCode);
if (response.IsSuccessStatusCode)
{
//ComicModel comic = await response.Content.ReadAsAsync<ComicModel>();
var responseString = await response.Content.ReadAsStringAsync();
return response;
}
else
{
Console.WriteLine("postRequest -> exception -> " + response);
throw new Exception(response.ReasonPhrase);
}
}
}

(3(

using (HttpResponseMessage response = await ApiHelper.apiClient.PostAsync(url, new FormUrlEncodedContent(param)))
{
Console.WriteLine("postRequest -> StatusCode -> " + response.StatusCode);
if (response.IsSuccessStatusCode)
{
//ComicModel comic = await response.Content.ReadAsAsync<ComicModel>();
var responseString = await response.Content.ReadAsStringAsync();
return response;
}
else
{
Console.WriteLine("postRequest -> exception -> " + response);
throw new Exception(response.ReasonPhrase);
}
}

所有解决方案都回复了我400个糟糕的请求
我的参数是:

var params= new List<KeyValuePair<string, string>>();
params.Add(new KeyValuePair<string, string>("grant_type", "password"));
params.Add(new KeyValuePair<string, string>("username", HttpUtility.UrlEncode("myUsername")));
params.Add(new KeyValuePair<string, string>("password", HttpUtility.UrlEncode("myPass")));

我该怎么修?提前谢谢。

如何与Postman进行身份验证?我在你的代码中看不到它。这取决于api的配置方式。请确保在客户端调用中使用适当的auth方法,例如Bearer令牌。Api应该返回400而不是401。

httpClient.SetBearerToken(accessToken);

哎呀!我的基本url以http开头。我忘了用https替换它。使用https一切都很好。:(
谢谢

最新更新