下面是一个例子:
using Microsoft.AspNetCore.Mvc;
/// <summary>
/// Eviget controller used for uploading artefacts
/// Either from teamcity or in case of the misc files
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class UploadDemoController : ControllerBase
{
[HttpPost]
public IActionResult Upload([FromForm] UploadContent input)
{
return Ok("upload ok");
}
}
public class UploadContent
{
public string Id { get; set; }
public string Name { get; set; }
public Stream filecontent { get; set; }
}
以下代码用于上载MultipartFormDataContent
using System.Net.Http.Headers;
HttpClient http = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
StringContent IdStringContent = new StringContent(Guid.NewGuid().ToString());
form.Add(IdStringContent, "Id");
StringContent NameStringContent = new StringContent($@"foobar");
form.Add(NameStringContent, "Name");
StreamContent TestStream = new StreamContent(GenerateStreamFromString("test content of my stream"));
TestStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "filecontent", FileName = "test.txt" };
TestStream.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(TestStream, "filecontent");
//set http heder to multipart/form-data
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
try
{
System.Console.WriteLine("start");
var response = http.PostAsync("http://localhost:5270/api/UploadDemo/Upload", form).Result;
response.EnsureSuccessStatusCode();
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
默认情况下,响应为400(错误请求)。
使用下面的控制器选项,请求被发送到rest服务器,这个选项只是说rest服务器应该忽略空值。
builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true)
流始终为空。(注意:其他值设置正确)
但流实际上是多部分表单数据(fiddler输出)
的一部分
在这种情况下,我需要做什么才能正确Map流?
2条答案
按热度按时间dhxwm5r41#
请使用IFormFile,而不要使用数据类型Stream。
因此,您可以按如下方式访问属性和文件:
要将文件持久化/保存到磁盘,可以执行以下操作:
wlwcrazw2#
这是一个基于ibarcia信息的样本。
我已经创建了两个webapi控制器,允许读取作为MultipartFormDataContent的一部分上传的文件。
第一个方法定义一个属性为[FromForm]的参数,该参数包含IFormFile类型的属性。在第二个实现中,未指定参数,可以通过Request.ReadFormAsync读取文件,然后访问文件