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