[英]HttpClient PostAsync returns 500 when getting token
I am trying to figure out what I can do (logging, things to check) before having to read server logs as I don't want to miss something stupid before requesting that.我试图在必须阅读服务器日志之前弄清楚我可以做什么(日志记录,要检查的事情),因为我不想在请求之前错过一些愚蠢的事情。
Here is my code:这是我的代码:
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;
I am a little newer to this so I'm not sure what to check next but have tried the same request using postman and get a response with my token so it looks like I am missing something or maybe formatting something incorrectly?我对此有点新,所以我不确定接下来要检查什么,但是使用邮递员尝试了相同的请求并使用我的令牌获得响应,所以看起来我遗漏了某些东西或者格式不正确?
我没有对我的参数进行 URL 编码,这是修复方法(可能是更好的方法)。
string urlParameters = string.Format("grant_type=password&username={0}&password={1}", Uri.EscapeDataString(username), Uri.EscapeDataString(password));
I was following an online course, and the code for setting the URL parameters were set like this:我正在学习一个在线课程,设置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);
}
}
}
When testing, found that 500 error was being returned for the PostAsync call.测试时,发现 PostAsync 调用返回 500 错误。 I checked my URL address and parameters and they all looked correct.我检查了我的 URL 地址和参数,它们看起来都正确。 If I tested in Swagger, then I received a 200 status and token was shown.如果我在 Swagger 中进行测试,那么我会收到 200 状态并显示令牌。
Following the link by Thomas Levesque I changed how the data variables were set to :按照 Thomas Levesque 的链接,我更改了数据变量的设置方式:
var data = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "password",
["username"] = username,
["password"] = password
});
Now the response status is 200 and the AuthenticatedUser model is populated correctly.现在响应状态是 200 并且正确填充了 AuthenticatedUser 模型。 However I couldn't understand why Dictionary seem to work and KeyValuePair didn't.但是我不明白为什么 Dictionary 似乎有效而 KeyValuePair 没有。 So I created the list and then encoded it:所以我创建了列表,然后对其进行了编码:
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))
This also worked.这也奏效了。 I freely admit that I do not fully understand why.....yet.我坦率地承认我不完全理解为什么.......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.