我有一个接受 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/