如何使用HttpClient发布表单数据IFormFile? [英] How to post form-data IFormFile with HttpClient?

查看:787
本文介绍了如何使用HttpClient发布表单数据IFormFile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有后端端点Task<ActionResult> Post(IFormFile csvFile),我需要从HttpClient调用此端点.目前,我正在获取Unsupported media type error. 这是我的代码:

I have backend endpoint Task<ActionResult> Post(IFormFile csvFile) and I need to call this endpoint from HttpClient. Currently I am getting Unsupported media type error. Here is my code:

var filePath = Path.Combine("IntegrationTests", "file.csv");
var gg = File.ReadAllBytes(filePath);
var byteArrayContent = new ByteArrayContent(gg);
var postResponse = await _client.PostAsync("offers", new MultipartFormDataContent
{
    {byteArrayContent }
});

推荐答案

您需要在MultipartFormDataContent集合中指定匹配动作参数名称(csvFile)的参数名称和随机文件名

You need to specify parameter name in MultipartFormDataContent collection matching action parameter name (csvFile) and a random file name

var multipartContent = new MultipartFormDataContent();
multipartContent.Add(byteArrayContent, "csvFile", "filename");
var postResponse = await _client.PostAsync("offers", multipartContent);

或同等

var postResponse = await _client.PostAsync("offers", new MultipartFormDataContent {
    { byteArrayContent, "csvFile", "filename" }
});

这篇关于如何使用HttpClient发布表单数据IFormFile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆