使用 HttpClient 将 Zip 文件上传到 ASP.NET 核心 WebAPI 服务,但 IFormData 参数始终为空

Upload Zip files to ASP.NET Core WebAPI service with HttpClient but IFormData argument is always null

正如标题所说,我正在尝试将 .zip 从我的 WPF 应用程序上传到我的 .NET Core Web API。

经过一些研究,我发现可以使用 MultiPartDataContent 并以这种方式发送它。

向服务器发送数据的代码如下所示:

            {
                client.BaseAddress = new Uri("http://localhost:62337/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                string filepath = @"C:\Users\uic10950\Desktop\Meeting2Text\RecordingApp\bin\mixedaudio.zip";
                string filename = "mixedaudio.zip";

                MultipartFormDataContent content = new MultipartFormDataContent();
                ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));

                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
                content.Add(fileContent);

                HttpResponseMessage response = await client.PostAsync("api/transcriptions/recording", content);
                string returnString = await response.Content.ReadAsAsync<string>();
            }

在服务器端,我的控制器操作如下所示:

        public async Task<IActionResult> AddFileToTranscription([FromForm] IFormFile file)
        {
            using (var sr = new StreamReader(file.OpenReadStream()))
            {
                var content = await sr.ReadToEndAsync();
                return Ok(content);
            }
        }

一旦我开始上传文件,此操作代码就会更改

根据我在研究时的理解,我的文件应该位于:

[FromForm] IFormFile

动作的文件属性,可惜为空

你做错了几件事:

public async Task<IActionResult> AddFileToTranscription([FromForm] IFormFile file)

❌ 你不需要 [FromFile] 属性。

❌你的文件参数名称是file但是你在上传文件的时候没有定义它,在客户端

❌ 您不需要添加 ContentDisposition 并将其设置为 attachment 因为它是为了响应,而不是请求! (1)


✅ 服务器:

public async Task<IActionResult> AddFileToTranscription( IFormFile file)
{
    using (var sr = new StreamReader(file.OpenReadStream()))
    {
        var content = await sr.ReadToEndAsync();
        return Ok(content);
    }
}

✅ 客户:

client.BaseAddress = new Uri("http://localhost:62337/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

string filepath = @"C:\Users\uic10950\Desktop\Meeting2Text\RecordingApp\bin\mixedaudio.zip";
string filename = "mixedaudio.zip";

MultipartFormDataContent content = new MultipartFormDataContent();
ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));

// ➡ ✅ important change fileContent, form-input-name, real-file-name
content.Add(fileContent, "file", filename);

HttpResponseMessage response = await client.PostAsync("api/transcriptions/recording", content);
string returnString = await response.Content.ReadAsAsync<string>();

MultipartFormDataContent.Add 方法有几个用于添加 form-data 的重载,您必须使用此 overload:

public void Add (System.Net.Http.HttpContent content, string name, string fileName);

结论:

无论您的 IFormData 参数是什么,您都需要使用该名称上传或发送请求!


  1. 在常规 HTTP 响应中,Content-Disposition 响应 header 是一个 header 指示内容是否期望在浏览器中内联显示,即作为 Web下载并保存在本地的页面或作为网页的一部分或作为附件。