将整数列表传递给C#控制器操作

时间:2017-12-07 03:25:46

标签: c# asp.net http controller http-post

我正在尝试将整数列表传递给C#控制器操作。我有以下代码:

    HttpRequestMessage request;
    String myUrl = 'http://path/to/getData';
    List<int> data = new List<int>() { 4, 6, 1 };

    request = new HttpRequestMessage(HttpMethod.post, myUrl);
    request.Content = new StringContent(JsonConvert.SerializeObject(data, Formatting.Indented));

    HttpResponseMessage response = httpClient.SendAsync(request).Result;
    String responseString = response.Content.ReadAsStringAsync().Result;
    var data = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(responseString);

控制器操作:

    [HttpPost]
    [ActionName("getData")]
    public Response getData(List<int> myInts) {

        // ...

    }

但结果responseString是:

 {"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'text/plain'.","ExceptionType":"System.InvalidOperationException}

2 个答案:

答案 0 :(得分:0)

this question类似 - 您没有发送List<int>,而是发送序列化的整数列表(在本例中为JSON序列化字符串)。因此,您需要在另一端接受字符串并反序列化,以及处理可能遇到的任何非整数值。像这样:

[HttpPost]
[ActionName("getData")]
public Response getData(string myInts) {

    var myIntsList = JsonConvert.DeserializeObject<List<int>>(myInts);
    // Don't forget error handling!

}

编辑2:

另一种选择是添加多个查询参数,如下所示:

http://path/to/getData?myInts=4&myInts=6&myInts=1

这应该适用于您已经拥有的代码。 ASP.NET可以将多个查询参数解释为List<T>)。

抱歉,您可能需要为解决方案添加[FromUri]属性:

[HttpPost]
[ActionName("getData")]
public Response getData([FromUri]List<int> myInts) {

    // ...

}

答案 1 :(得分:0)

如果您在客户端应用程序中使用Microsoft.AspNet.WebApi.Client

,这很容易

行动方法

// POST api/values
        public void Post(List<int> value)
        {
        }

客户端应用程序

class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                var result = client.PostAsJsonAsync("http://localhost:24932/api/values",
                    new List<int>() {123, 123, 123}).Result;

                Console.ReadLine();
            }
        }
    }