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

Mar*_*nic 0 c# wpf dotnet-httpclient asp.net-core-webapi

正如标题所说,我正在尝试将 .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>();
            }
Run Code Online (Sandbox Code Playgroud)

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

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

一旦文件上传工作,此操作代码将更改

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

[FromForm] IFormFile

动作的文件属性,但不幸的是它是空的。

Ali*_*ami 7

你做错了几件事:

public async Task<IActionResult> AddFileToTranscription([FromForm] IFormFile file)
Run Code Online (Sandbox Code Playgroud)

? 你不需要[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

? 客户:

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

Run Code Online (Sandbox Code Playgroud)

MultipartFormDataContent.Add方法有几个用于添加表单数据的重载,您必须使用此重载

public void Add (System.Net.Http.HttpContent content, string name, string fileName);
Run Code Online (Sandbox Code Playgroud)

结论:

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


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