【问题标题】:No mediatype formatter found找不到媒体类型格式化程序
【发布时间】:2015-11-02 22:05:09
【问题描述】:

我正在尝试调用此方法

    [HttpGet]
    [Route("api/Trinity/GetDirectoryAndTask/{modelTemplateId}/{taskName}")]
    public KeyValuePair<string, string> GetDirectoryAndTask(int modelTemplateId, string taskName)

使用 url http://localhost:46789/api/Trinity/GetDirectoryAndTask/9/AG33%2f34 但我得到一个“MediaTypeFormatter 可用于从媒体类型为'text/html'的内容中读取类型为'KeyValuePair`2'的对象”异常。

【问题讨论】:

标签: c# asp.net-web-api


【解决方案1】:

由于在路由值中使用了/%2f,我怀疑服务器端的主要问题应该是:

HTTP 错误 404.0 - 未找到
您要查找的资源已被删除、名称已更改或暂时不可用。

要解决它,您可以将路由更改为:

api/Trinity/GetDirectoryAndTask/{modelTemplateId}/{*taskName}

要测试服务器端是否正常,请将url粘贴到浏览器中并获取结果。


但对于您的客户端,错误与您从该 api 读取数据的方式有关。我使用此代码并在更改路线后读取数据:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(" http://localhost:46789/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = await client.GetAsync("api/Trinity/GetDirectoryAndTask/9/AG33%2f34");
    if (response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsAsync<KeyValuePair<string, string>>();
        //The result is a valid key/value pair
    }
}

【讨论】:

    猜你喜欢
    • 2013-07-09
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多