c# - 将整数列表传递给 C# Controller 操作

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

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

    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);

Controller Action :

    [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}

最佳答案

类似于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) {

    // ...

}

关于c# - 将整数列表传递给 C# Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687097/

相关文章:

c# - RSS C# 获取汇率

c# - 构建非重组三叉树时如何避免 C# 中的 System.OutOfMemoryException

c# - 单击按钮时 Gridview 颜色不会改变

python - Tornado AsyncHTTPClient 是否支持持久连接?

c# - 为什么 DateTimeInfo.MonthNames 返回 13 个成员?

c# - 为什么在 Java 方法重载中不考虑返回类型?

asp.net - 在VSO上构建ASP.NET 5 beta 7应用程序有运气吗?

javascript - 没有在 ASP.Net 中获取 ClientID

wcf - 如何在自定义 WCF HTTP 绑定(bind)中存储 header 信息

javascript - 从 javascript 获取 HTTP Basic Auth 用户名?