简体   繁体   English

如何将数组从HttpClient发布到Web api控制器?

[英]How do I POST an array to a web api controller from an HttpClient?

Inside a web api controller I have the following method: 在Web API控制器内部,我具有以下方法:

[HttpPost]
public ProcessResultDto Process(int[] IDs)
{
}

I cannot change that signature or dll or anything. 我无法更改该签名或dll或其他任何内容。

I have to make an executable that calls that method. 我必须制作一个调用该方法的可执行文件。

Here's roughly what I have so far: 到目前为止,大致是这样的:

int[] ids = //...
using (var client = new HttpClient())
{
    var content = // I don't know what goes here.
    var result = cli.PostAsync("/api/Processor/Process", content).Result;
    string resultContent = result.Content.ReadAsStringAsync().Result;
    // Substring(6) because of leading )]}',\n
    var summary = JsonConvert.DeserializeObject<ProcessResultDto>(resultContent.Substring(6));
    return summary;
}

What do I set content to so that I can pass an array of int's to my web api controller 我将内容设置为什么,以便可以将int数组传递给Web api控制器

You could do the following: 您可以执行以下操作:

int[] ids = new[] {1,2,3,4};
var content = JsonConvert.SerializeObject(new {
   IDs = ids
});

This will create an anonymous object with a property of IDs and convert it to json. 这将创建一个具有IDs属性的匿名对象,并将其转换为json。 The json will look like: json看起来像:

{
    IDs: [1,2,3,4]
}

The web API method will then bind that to your model. 然后,Web API方法会将其绑定到您的模型。

I use ServiceStack 's JSON serializer/deserializer as they're the current .Net performance champ. 我使用ServiceStack的JSON序列化器/反序列化器,因为它们是当前的.Net性能冠军。 From the ServiceStack docs 来自ServiceStack文档

Any List, Queue, Stack, Array, Collection, Enumerables including custom enumerable types are stored in exactly the same way as a JavaScript array literal 任何列表,队列,堆栈,数组,集合,可枚举(包括自定义可枚举类型)的存储方式都与JavaScript数组文字完全相同

Therefore 因此

int[] ids = [1,2,3,4];
var content = TypeSerializer.SerializeToString(new {IDs=ids});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM