Shabar
Shabar

Reputation: 2821

Http client Post with body parameter and file in c#

I was trying to attach a csv file as a body parameter in my test script. But still as per the below code controller expect file and just curious how should I pass that.

I run test script in below order

Method-1

public void AttachedRatesFile(string fileName)
            {            
                _form = string.IsNullOrWhiteSpace(fileName)
                    ? _form = new StringContent(string.Empty)
                    : _form = new StreamContent(File.OpenRead($"{ResourceFolder}{fileName}"));
                _form.Headers.ContentType = new MediaTypeHeaderValue("application/csv");
                _form.Headers.ContentDisposition = new ContentDispositionHeaderValue(fileName);
            }

Method-2

        public void PostRequestExecutes(string resource)
        {
            var content = new MultipartFormDataContent{_form};
            WhenThePostRequestExecutesWithContent(resource, content);
        } 

Method-3

public async void WhenThePostRequestExecutesWithContent(string resource, HttpContent content)
{
    ResponseMessage = await HttpClient.PostAsync(resource, content);
}

I see null in below file parameter

Controller:

public async Task<IActionResult> SeedData(IFormFile file)
{
    var result = await _seedDataService.SeedData(file);
    return Ok(new { IsUploadSuccesful = result});
}

Upvotes: 0

Views: 2218

Answers (1)

Rav
Rav

Reputation: 705

I would add that to the body as a stream

var memoryContentStream = new MemoryStream();

using (var streamWriter = new StreamWriter(memoryContentStream, Encoding.UTF8, 1000, 
true))
{
  using (var jsonTextWriter = new JsonTextWriter(streamWriter))
  {
    var jsonSerializer = new JsonSerializer();

    jsonSerializer.Serialize(jsonTextWriter, OBJECT);
    jsonTextWriter.Flush();
  }
}

if (memoryContentStream.CanSeek)
{
  memoryContentStream.Seek(0, SeekOrigin.Begin);
}

Then

using (var streamContent = new StreamContent(memoryContentStream))
            {
                streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                request.Content = streamContent;

                using (var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
                {
                    var stream = await response.Content.ReadAsStreamAsync();

                    response.EnsureIsSuccessStatusCode();

                }
            }

The above would first write the content as a memory stream and then when creating the POST request you can send the stream as a streamContent

Upvotes: 1

Related Questions