具有C#中的body参数和文件的Http客户端发布

时间:2019-05-22 10:03:57

标签: c# httpclient

我试图在测试脚本中附加一个csv文件作为正文参数。但是仍然按照下面的代码控制器的期望文件,只是好奇我应该如何传递它。

我按以下顺序运行测试脚本

方法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);
            }

方法2

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

方法3

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

我在下面的文件参数中看到空值

控制器:

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

1 个答案:

答案 0 :(得分:1)

我会将其作为流添加到正文

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);
}

然后

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();

                }
            }

上面的内容首先将内容写为内存流,然后在创建POST请求时可以将流作为streamContent发送