为什么我在此请求中获得不支持的媒体类型?

时间:2018-03-23 06:42:18

标签: asp.net-mvc asp.net-core-mvc

我正在从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错误?

1 个答案:

答案 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接受requestUricontent的参数,您的代码缺少Absolute requestUri