Home > Software design >  How to Send IFormFile in a modal class from c# client to the Web API?
How to Send IFormFile in a modal class from c# client to the Web API?

Time:09-17

So, I am trying to send IFormFile type data present in a modal class from a c# client to the web api in Asp.net core. Here is the code for my modal

public class EmployeeRequestModel
    {
        public string empName { get; set; }
        public string location { get; set; }
        public IFormFile imageFile { get; set; }
   }

and this is how my API looks like in Asp.Net Core

[HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public IActionResult Post([FromForm]EmployeeRequestModel requestModel)
        {
        }

and i am calling this API from my c# client like this,

var modal = new[]
            {
                new KeyValuePair<string, string>("empName",model.empName),
                new KeyValuePair<string, string>("location",model.location),
                 new KeyValuePair<string, IFormFile>("location",model.imageFile),
            };
            var response = await _httpClient.PostAsync(baseUrl, new FormUrlEncodedContent(modal));

but this is not working since it only accepts key value pair of type<string,string> and not IFormFile, So, How can i send IFormFile in this scenario ??

CodePudding user response:

ok,I have fixed the issue with MultipartFormDataContent class, so it allowed me to send IFormFile to the Web API alongside other data types, this is how i fixed it,

           MultipartFormDataContent form = new MultipartFormDataContent();
            HttpContent content = new StringContent("imageFile");
            form.Add(content, "imageFile");
            var stream = new FileStream("D:\\ang\\licensed-image.jpg", FileMode.Open);
            model.imageFile = new FormFile(stream, 0, stream.Length, "name","test");
            content = new StreamContent(stream);
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "imageFile",
                FileName = model.imageFile.FileName
            };

            form.Add(new StringContent(model.empName),"empName");
            form.Add(new StringContent(model.location),"location");
            form.Add(content);
            var response = await _httpClient.PostAsync(baseUrl, form);
       
  • Related