首页 文章

无法使用C#客户端将IFormFile发送到ASP.Net Core Web API

提问于
浏览
1

我有一个ASP.Net核心Web API,控制器POST方法定义如下:

[HttpPost("SubmitFile")]
public async Task<IActionResult> SubmitFile(IFormFile file)
{
}

我有一个客户端方法来调用API SubmitFile()方法,定义如下:

[HttpPost]
public async Task<IActionResult> Index(ICollection<IFormFile> files)
{
     using (var client = new HttpClient())
     {
         client.BaseAddress = new Uri(_options.SiteSpecificUrl);

         foreach (var file in files)
         {
             if (file.Length <= 0)
                 continue;

             var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
             var fileContent = new StreamContent(file.OpenReadStream());
             fileContent.Headers.Add("X-FileName", fileName);
             fileContent.Headers.Add("X-ContentType", file.ContentType);

             var response = await client.PostAsync(_options.WebApiPortionOfUrl, fileContent);
         }
     }

    return View();
}

执行客户端发送时,在服务器端,SubmitFile()中的断点显示file参数为null . 我怎样才能正确发送文件?保留服务器端API很重要,因为我让Swashbuckle / Swagger正确生成可以发送文件的UI .

1 回答

  • 4

    我发现了几种方法 . 这是最简单的 . 请注意,这是一个ASP.Net Core客户端解决方案:

    [HttpPost]
    public async Task<IActionResult> Index(ICollection<IFormFile> files)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(_options.SiteSpecificUrl);
    
            foreach (var file in files)
            {
                if (file.Length <= 0)
                    continue;
    
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
    
                using (var content = new MultipartFormDataContent())
                {
                    content.Add(new StreamContent(file.OpenReadStream())
                    {
                        Headers =
                        {
                            ContentLength = file.Length,
                            ContentType = new MediaTypeHeaderValue(file.ContentType)
                        }
                    }, "File", fileName);
    
                    var response = await client.PostAsync(_options.WebApiPortionOfUrl, content);
                }
            }
        }
    }
    

    从.cshtml页面调用此控制器方法,如下所示:

    @{
        ViewData["Title"] = "Home Page";
    }
    
    <form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data">
        <input type="file" name="files" multiple />
        <input type="submit" value="Upload" />
    </form>
    

    此表单显示两个按钮,“选择文件”,其中显示“选择文件”对话框,以及“上载”,它调用HomeController.Index方法 .

相关问题