[英]HttpClient PostAsync returns 500 when getting token
我试图在必须阅读服务器日志之前弄清楚我可以做什么(日志记录,要检查的事情),因为我不想在请求之前错过一些愚蠢的事情。
这是我的代码:
const string URL = "https://SomeURL/api/security/";
string urlParameters = string.Format("grant_type=password&username={0}&password={1}", username, password);
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");
var tokenResponse = client.PostAsync("token", content).Result;
我对此有点新,所以我不确定接下来要检查什么,但是使用邮递员尝试了相同的请求并使用我的令牌获得响应,所以看起来我遗漏了某些东西或者格式不正确?
我没有对我的参数进行 URL 编码,这是修复方法(可能是更好的方法)。
string urlParameters = string.Format("grant_type=password&username={0}&password={1}", Uri.EscapeDataString(username), Uri.EscapeDataString(password));
我正在学习一个在线课程,设置URL参数的代码是这样设置的:
public async Task<AuthenticatedUser> Authenticate(string userName, string password)
{
var data = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username ", "userName"),
new KeyValuePair<string, string>("password", "password")
});
using (HttpResponseMessage response = await apiClient.PostAsync("/Token", data))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<AuthenticatedUser>();
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
测试时,发现 PostAsync 调用返回 500 错误。 我检查了我的 URL 地址和参数,它们看起来都正确。 如果我在 Swagger 中进行测试,那么我会收到 200 状态并显示令牌。
按照 Thomas Levesque 的链接,我更改了数据变量的设置方式:
var data = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "password",
["username"] = username,
["password"] = password
});
现在响应状态是 200 并且正确填充了 AuthenticatedUser 模型。 但是我不明白为什么 Dictionary 似乎有效而 KeyValuePair 没有。 所以我创建了列表,然后对其进行了编码:
var dataList = new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
};
var content = new FormUrlEncodedContent(dataList);
using (HttpResponseMessage response = await apiClient.PostAsync(requestUrl, content))
这也奏效了。 我坦率地承认我不完全理解为什么.......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.