我在从C#创建POST请求以生成令牌时遇到问题。该服务没有错,因为我可以使用Postman来使用它。
有人可以帮帮我吗。
按照我的编码。每次出现403错误。
public async Task<string> LoginAsync(string userName, string password)
{
try
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var request = new HttpRequestMessage(HttpMethod.Post, login_url);
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var authenticationBytes = System.Text.Encoding.ASCII.GetBytes("----------username-------- : ----------pwd----------");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authenticationBytes));
//request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(authenticationBytes));
var response = await client.SendAsync(request);
var jwtResponse = await response.Content.ReadAsStringAsync(); // contains access token
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(jwtResponse);
accessToken = jwtDynamic.Value<string>("access_token");
Debug.WriteLine(jwtResponse);
}
catch (Exception e)
{
Console.WriteLine(e);
}
return accessToken;
}
以下是Postman的屏幕截图。
非常感谢。