c# - 如何在 MultipartFormData 中传递字典?

标签 c# asp.net-core .net-core asp.net-core-webapi

我有一个接受 IFormFile 的 Controller 和一个使用表单数据的对象(一个名为 Document 的类)。

这是 Controller :

[HttpPost]
public async Task<IActionResult> Post(IFormFile file, [FromForm] Document document, CancellationToken token = default)
{
    ...
}

这就是Document类看起来像:

public class Document
{
    public Guid DocumentId { get; set; }
    public string Name { get; set; }
    public DocumentType DocumentType { get; set; } = DocumentType.Unsorted;
    public Dictionary<string, string> Metadata { get; set; } = new Dictionary<string, string>();
}

这是 POST 的代码s 到所述 Controller 的数据:

using (var multipartContent = new MultipartFormDataContent())
{
    multipartContent.Add(new StringContent(document.DocumentId.ToString()), FormDataKeys.DocumentId);
    multipartContent.Add(new StringContent(document.DocumentType.ToString()), FormDataKeys.DocumentType);
    multipartContent.Add(new StreamContent(file), FormDataKeys.File, document.Name);

    using (var apiResult = await _httpClient.PostAsync("api/documents", multipartContent, token))
    {
        var content = await apiResult.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<StoreDocumentResult>(content);
    }
}

这有效,IFormFile[FromForm] Document 的属性 Controller 中的参数在我发送POST请求时填写。只是,我不知道如何填写 Metadata Document 的属性(property)?我怎样才能通过 Dictionary<string, string>MultipartFormData

最佳答案

最简单的方法是用 JSON 将字典序列化为字符串,然后反序列化。

     var settings = new JsonSerializerSettings();
    settings.Formatting = Formatting.Indented;
    settings.ContractResolver = new DictionaryAsArrayResolver();

    // serialize
    string json = JsonConvert.SerializeObject(Document.Metadata, settings);

   multipartContent.Add(new StringContent(json ), FormDataKeys.Metadata );

要反序列化它,你可以使用这样的东西:

var d  = JsonConvert.DeserializeObject<Dictionary<String,String>>(json, settings);

另一种选择是继承 HttpContent 并重写 SerializeToStreamAsync 方法。在这种情况下,您可以随意写入提供的缓冲区。

class DictionaryContent: HttpContent
{
   public Object Value { get; }

   public DictionaryContent( Object value)
   {
       Value = value;
       Headers.ContentType = .. You must provide the desired content type.
   }

   protected override Task SerializeToStreamAsync( Stream stream, TransportContext context )
   {
        using ( var buffer = new BufferStreamWriter( stream, 4096 ) )
        {
            var writer = new JsonWriter( buffer, JsonSettings.Default );
            writer.WriteValue( Value ); // HERE You can do anything that you want.
        }

        return Task.CompletedTask;
   }
}

关于c# - 如何在 MultipartFormData 中传递字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55375209/

相关文章:

azure - 如何在 Azure 网站中禁用 HTTPS 重定向

c# - 使用 ActivatorUtilities.CreateInstance 从类型创建实例

c# - .net Core Quartz 依赖注入(inject)

c# - 点网核心 3.1 : How to use AddJsonFile with absolute path to file?

c# - UWP 应用堆栈跟踪中的行号

c# - 启动 Contract First WCF 或 Web 服务的最佳方式?

c# - Rx 如何按键对一个复杂对象进行分组,然后在没有 "stopping"流的情况下执行 SelectMany?

c# - 更改呈现 View Controller 约束

c# - 使用 PowerShell Split 和正则表达式在正则表达式匹配后返回所有内容

c# - 在第一次加载之前通过授权服务器保护 SPA