简体   繁体   中英

C# HttpClient send multiform post data

I'm having some issues with calling an API. I need to send post data containing 2 things: an ID and an array of strings.

I have tried a lot of things, all resulting in errors or simply not sending data in the right way. All answers I found, do not handle the fact that I want to send 2 different data types.

My current C# code is like this:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(SERVER_URI);
var content = ; //This is where I need help
HttpResponseMessage response = client.PostAsync("API URL", content).Result;

The API function is set up like this:

public ActionResult Function(int Id, string[] array)
{
    // Contents are not relevant
}

The problem here is that I need to be able to set the names for the values. I have tried serializing the required data to Json with the following code:

StringContent content = new System.Net.Http.StringContent(TypeSerializer.SerializeToString(new { Id = Id, array = array }));

Of course, Id and Array in this example are filled variables. This results in a successful call to the server, but the server does not receive the data correctly (both variables stay null)

I've also tried doing it with MultiPartContent, but once again I don't see any way to actually give the right names to the values (Every attempt once again results in the API receiving null values)

Edit:

I got it to send the Id using MultipartFormDataContent instead.

MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent(Id), "Id");

I still can't seem to get it to send an array to the server though.

Wrap things into an object like this

public class MyPostObject
{
    public int Id{get;set;}
    public IEnumerable<string> Array{get;set;}
}

then send it as json

using (var client = new HttpClient())
{
    var myObject = new MyPostObject(){Id =XXXX, Array = YYYYY};
    using (var response = await client.PostAsJsonAsync("api/CONTROLLER/METHOD", myObject))
    using (var content = response.Content)
    {
        var result = content.ReadAsAsync<LoginModelResponse>().Result;
    }
}

and receive it as json like this in the server

[HttpPost]
public dynamic METHOD([FromBody] MyPostObject mydata)
{
    //Do whatever
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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