简体   繁体   中英

asp.net core web api how to send json object from client side c#

this is my client code

var client = new HttpClient();
            client.BaseAddress = new Uri(BASE_URL);
            var multipart = new MultipartFormDataContent();
            var jsonToSend = JsonConvert.SerializeObject(template, Formatting.None);
            var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json");
            multipart.Add(body, "JsonDetails");
            return client.PostAsync("jsons", multipart);

server code is

 [HttpPost("jsons")]
        public async Task<IActionResult> RequestJson([FromBody]Person person)
        {

        if (person != null)
        {
            return Ok("true");
        }


        return Ok("false");

person code

public class Person
    {
        public string Name { get; set; }
        public string Position { get; set; }
    }

when look in debug my post from client dont knock to server, in postman my post sending and i can see my object property

Just post the StringContent directly without the Multipart-Form:

var client = new HttpClient
{
    BaseAddress = new Uri(BASE_URL)
};

var jsonToSend = JsonConvert.SerializeObject(template, Newtonsoft.Json.Formatting.None);

var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json");

return client.PostAsync("jsons", body)

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