【问题标题】:Send and Receive an IList<int> with ASP.NET Web Api使用 ASP.NET Web Api 发送和接收 IList<int>
【发布时间】:2014-05-10 23:50:36
【问题描述】:

我需要向我的 Web API 发送和接收 IList:

API方法:

public IList<int> GetKeywordIdsFromIds([FromUri]List<int> ids)
{
     // this methods retuns null or an IList<int>
     return _iKeywordService.GetKeywordIdsFromIKeywordIds(ids);
}

调用方法:

public List<int> GetKeywordIdsFromIds(IList<int> iKeywordIds)
{
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(API_BASE_URL);
            client.DefaultRequestHeaders.Accept.Clear();

            return client.GetAsync(url + iKeywordIds).Result.Content.ReadAsAsync<List<int>>().Result;
        }
}

我得到错误:

Exception:Thrown: "No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'text/html'." (System.Net.Http.UnsupportedMediaTypeException)

编辑:

我不知道这是否有帮助,但我是从 IIS 日志文件中获得的:

2014-03-31 16:11:31 127.0.0.1 GET /api/ikeyword/getkeywordidsfromids/System.Collections.Generic.List`1[System.Int32] - 80 - 127.0.0.1 - 404 0 2 1

EDIT2:

默认路线:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

【问题讨论】:

  • 查看这篇文章,如何在代码中添加参数:stackoverflow.com/questions/217070/…
  • 这是 ConsoleApp 和 MVC Web App 之间的调用,因此您可以在问题中看到传递信息。真不知道是不是他问的。抱歉...我认为问题在于调用“url + iKeywordIds”,因为如果我尝试使用 url +“/1”,它可以正常工作
  • 您的 API 函数可能需要一个类似于 .../api/controllername?ids=1&ids=2&ids=3 的 URL。您需要将客户端上的 List 转换为函数期望的查询字符串
  • 您编写一些代码来解析您的列表并生成所需的查询字符串。例如,stackoverflow.com/questions/17096201/…
  • 这个参数叫ids,不是iKeywordIds。而且我也不相信 URL 的其余部分是正确的。浏览到您网站的根目录并使用内置的 web api 文档来获取正确的 URL。

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


【解决方案1】:

要使用查询字符串中的ints 列表调用 Web API 操作,请执行以下操作...

/api/ikeyword/getkeywordidsfromids?ids=1&ids=3&ids=4

/api/ikeyword/getkeywordidsfromids?ids[]=1&ids[]=3&ids[]=4

从您的 IIS 日志看来,您需要在控制台应用程序中正确格式化列表并将其附加到 URL。您的调用代码应如下所示...

var parameters = ids.Select(id => string.Format("ids={0}", id)).ToArray();
var url = string.Format("/api/ikeyword/getkeywordidsfromids?{0}", string.Join("&", parameters));

【讨论】:

  • 您好,谢谢,如何处理 WebApi 方法中的值?
  • ids 应该是ints 的列表。你可以直接传给_iKeywordService.GetKeywordIdsFromIKeywordIds(ids)...
  • 它正在工作,请更正您的代码,以便我将您的答案设置为正确:删除 Format 方法中的“=”:getkeywordidsfromids?{0} 否则在 Api 中它不会收到第一个值
  • 是我谢谢你!
猜你喜欢
  • 2018-12-23
  • 1970-01-01
  • 2017-09-26
  • 2015-08-16
  • 1970-01-01
  • 2014-05-22
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多