asp.net core web api cant send object from client side

Viewed 443

this is server code who cath the request from client side

[HttpPost("Add")]
        public async Task<IActionResult> Add([FromBody]RequestAdd person)
        {

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

            return Ok("false");
        }

this is code is client post there i add to multipart json and image bytes

    public Task<HttpResponseMessage> Uploads(Person person, List<FileInfo> files)
            {


            try
            {
                var jsonToSend = JsonConvert.SerializeObject(person, Formatting.None);
                var multipart = new MultipartFormDataContent();

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


                foreach (var item in files)
                {
                    var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(item.FullName));

                    multipart.Add(fileContent, item.FullName);
                }


                var client = new HttpClient();
                client.BaseAddress = new Uri(BASE_URL);

                return client.PostAsync("Add", multipart);
            }
            catch
            {
                return null;
            }  
        }

code where i use this method there i have error

static void Main(string[] args)
                {
                    Method2();
                    Console.ReadLine();
                }

                static void Method2()
                {
                    UploadMultiPart uploadMultiPart = new UploadMultiPart();

                    List<FileInfo> fileInfos = new List<FileInfo>()
                    {
                        new FileInfo(@"C:\asd\full-metal-jacket.png"),
                        new FileInfo(@"C:\asd\full-metal-jacket.png"),
                        new FileInfo(@"C:\asd\full-metal-jacket.png")
                    };

                    Person person = new Person
                    {
                    Name = "Adilbek",
                    SureName = "Ramazanov",
                    Position = "God",
                    Group = "heaven",
                    Phone = 123123
                    };

                var result = loadMultiPart.Uploads(person,fileInfos).Result;
                Console.WriteLine("Status is " + result.StatusCode);
            }

error code is Status is UnsupportedMediaType

i dont have idea how to send to server, please help me sorry my bad english

1 Answers

Use the [FromForm] attribute, not [FromBody] attribute.

    [HttpPost("Add")]
    public async Task<IActionResult> Add([FromForm]RequestAdd person)
    {

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

        return Ok("false");
    }
Related