我创建了一个API和一个登录表单,我需要使用Username
和Password
属性授权对我的API的访问,这些属性是从我的登录表单中的两个文本框中获得的。但是,API的响应始终为空。这是我的原始代码:
public async Task<AuthenticatedUser> Authenticate(string username, string password)
{
var data = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username), //I made sure that both username and password
new KeyValuePair<string, string>("password", password) //are passed correctly to the Authenticate() void
};
var content = new FormUrlEncodedContent(data); //var data is not null but "content" is
using (HttpResponseMessage response = await apiClient.PostAsync("/token", content))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<AuthenticatedUser>(); //response is always "null"
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
我尝试用List<>
数组替换KeyValuePair<>
,也尝试使用Dictionary<string, string>
。这些选项均无效。在网上进行了一些研究之后,我看到了使用StringContent
或MediaFolder
的替代方法,但是我不知道如何使其与他们一起使用。
我也在我的域中使用https,所以那里似乎没有错误。目前,看来FormUrlEncodedContent
编码不正确。
此外,来自Swagger和Postman的请求返回值。
答案 0 :(得分:1)
我看到您从 Tim Corey 的 youtube 频道零售经理中完成了教程。 PostAsync
返回 null
时我也遇到了同样的问题。
设置断点到第throw new Exception(response.ReasonPhrase);
行时可以查看异常详情
在我的情况下,它在 DataManager 项目属性中设置为 SSL endabled 为 True,因此它使用安全协议打开 url - https。在 Tim 的教程中,您会看到 http 协议。
SSL Enabled: False
http://...
或选择覆盖应用程序根 URL:http://...
key="api" value="http://...
答案 1 :(得分:0)
首先,password
个授予类型仅接受表单编码application/x-www-form-urlencoded
,而不接受JSON编码application/JSON
。
您可以阅读有关here的更多信息,也可以尝试如下更改内容:
替换此:
var data = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username), //I made sure that both username and password
new KeyValuePair<string, string>("password", password) //are passed correctly to the Authenticate() void
};
var content = new FormUrlEncodedContent(data);
与此:
var content = new FormUrlEncodedContent(
new KeyValuePair<string, string>[] {
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
}
);