【问题标题】:Upload Zip files to ASP.NET Core WebAPI service with HttpClient but IFormData argument is always null使用 HttpClient 将 Zip 文件上传到 ASP.NET Core Web API 服务,但 FormData 参数始终为空
【发布时间】:2019-07-02 07:16:05
【问题描述】:

正如标题所说,我正在尝试将 .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

action的file属性,可惜是null。

【问题讨论】:

  • 你试过没有[FromForm]吗?
  • @Ali Bahrami 还是同样的问题,它保持为空

标签: c# wpf asp.net-core-webapi dotnet-httpclient


【解决方案1】:

你做错了几件事:

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 方法有几个重载用于添加表单数据,你必须使用这个overload

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

结论:

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


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

【讨论】:

  • 这正是我所需要的,感谢您提供如此有条理和详细的答案。
猜你喜欢
  • 2017-10-21
  • 2021-06-19
  • 2017-06-07
  • 2021-07-26
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
相关资源
最近更新 更多