【问题标题】:Howto upload MultipartFormDataContent which contains a stream using c# in webapi如何在 web api 中使用 c# 上传包含流的 MultipartFormDataContent
【发布时间】:2023-02-08 21:12:03
【问题描述】:

给出的是以下 webapi HttpPost 方法:

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(错误请求)。

使用以下控制器选项,请求将发送到其余服务器。这个选项只是说其余的服务器应该忽略空值。

 builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true)

流始终为空。 (注意:其他值设置正确)

但流实际上是多部分表单数据的一部分(提琴手输出)

在这种情况下,我需要做什么才能正确映射流?

【问题讨论】:

    标签: c# .net rest asp.net-web-api


    【解决方案1】:

    而不是使用数据类型溪流, 使用表单文件.

    然后您可以按如下方式访问属性和文件:

    var file = input.filecontent // This is the IFormFile file
    

    要将文件持久化/保存到磁盘,您可以执行以下操作:

    using (var stream = new FileStream(path, FileMode.Create))
    {
        await file.File.CopyToAsync(stream);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2018-10-25
      • 1970-01-01
      相关资源
      最近更新 更多