使用ASP.NET Web Api </int>发送和接收IList <int>

时间:2014-03-31 14:58:16

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

我需要向我的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 }
        );

1 个答案:

答案 0 :(得分:2)

要在查询字符串中使用int列表调用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));