HttpClient PostAsync 在获取令牌时返回 500



在不得不读取服务器日志之前,我试图弄清楚我能做什么(日志记录、要检查的事情(,因为我不想在请求之前错过一些愚蠢的事情。

这是我的代码:

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 参数的代码设置如下:

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,并且已正确填充身份验证用户模型。但是我不明白为什么字典似乎有效而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))

这也奏效了。我坦率地承认我不完全明白为什么.....还。

我没有

对我的参数进行 URL 编码,这是修复程序(可能是更好的方法(。

string urlParameters = string.Format("grant_type=password&username={0}&password={1}", Uri.EscapeDataString(username), Uri.EscapeDataString(password));

最新更新