无法使用C#客户端将IFormFile发送到ASP.Net Core Web API [英] unable to send IFormFile to ASP.Net Core Web API using C# client
问题描述
我有一个ASP.Net Core Web API,其控制器POST方法定义如下:
I have an ASP.Net Core Web API, with a controller POST method defined like this:
[HttpPost("SubmitFile")]
public async Task<IActionResult> SubmitFile(IFormFile file)
{
}
我有一个客户端方法来调用API SubmitFile()方法,其定义如下:
I have a client-side method to call the API SubmitFile() method, defined like this:
[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.
When the client send is performed, on the server side a break-point in SubmitFile() shows that the file argument is null. How can I correctly send the file? It is important to preserve the server-side API, as I have Swashbuckle/Swagger correctly generating a UI that can send the file.
推荐答案
我发现了几种方法.这是最简单的.请注意,这是一个ASP.Net Core客户端解决方案:
I've found a couple ways of doing this. Here is the simplest. Note that this is an ASP.Net Core client-side solution:
[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页中调用此控制器方法,如下所示:
This controller method is called from a .cshtml page as follows:
@{
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方法.
This form displays two buttons, "Choose Files", which presents a "select files" dialog, and "Upload", which calls the HomeController.Index method.
这篇关于无法使用C#客户端将IFormFile发送到ASP.Net Core Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!