【问题标题】:Pass a List of integers to a C# controller action将整数列表传递给 C# 控制器操作
【发布时间】:2017-12-07 03:25:45
【问题描述】:

我正在尝试将整数列表传递给 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}

【问题讨论】:

  • 如果其中一个答案对您有所帮助,请点赞并将其标记为答案。如果您的问题仍未得到解答,请告诉我们。如果您发现问题的不同答案,请将其作为答案发布。谢谢! :)

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


【解决方案1】:

类似于this question - 您发送的不是List&lt;int&gt;,而是一个序列化的整数列表(在这种情况下,是一个 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&amp;myInts=6&amp;myInts=1

这应该适用于您已有的代码。 ASP.NET 可以将多个查询参数解释为 List&lt;T&gt;)。

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

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

    // ...

}

【讨论】:

    【解决方案2】:

    如果您在客户端应用程序中使用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();
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-24
      • 2011-03-13
      • 2011-08-17
      • 1970-01-01
      • 2018-09-30
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多