我正在从WPF应用程序向作为API的MVC Core应用程序发出以下请求:
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("userName", userName),
new KeyValuePair<string, string>("password", password)
});
////var content = new StringContent($"{{\"username\": {userName}, \"password\": {password}}}", Encoding.UTF8, "application/json");
var resp = await _client.PostAsync("api/Token", formContent);
var json = await resp.Content.ReadAsStringAsync();
var tw = JsonConvert.DeserializeObject<TokenWrapper>(json);
return tw.Token;
当我使用断点检查resp
时,在PostAsync
调用后,我看到415 - Unsupported Media Type
错误。动作第一行的断点不是事件命中,所以我认为请求甚至没有到达控制器。
控制器操作如下所示:
public async Task<string> LoginAsync(string userName, string password)
{
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("userName", userName),
new KeyValuePair<string, string>("password", password)
});
////var content = new StringContent($"{{\"username\": {userName}, \"password\": {password}}}", Encoding.UTF8, "application/json");
var resp = await _client.PostAsync("api/Token", formContent);
var tempContent = await resp.Content.ReadAsStringAsync();
var json = await resp.Content.ReadAsStringAsync();
var tw = JsonConvert.DeserializeObject<TokenWrapper>(json);
return tw.Token;
}
我希望FormUrlEncodedContent
暗示内容类型和工作,就像我看到的大量示例一样。为什么我会收到415错误?
答案 0 :(得分:1)
尝试将Media Type
设置如下:
var content = new StringContent(formContent.ToString(), Encoding.UTF8, "application/json");
var result = await _client.PostAsync("http://example.com/api/Token", content);
同样PostAsync接受requestUri
和content
的参数,您的代码缺少Absolute
requestUri
。