Ben*_*min 5 c# .net-core asp.net-core asp.net-core-webapi
我有一个控制器,它使用表单数据接受一个IFormFile对象和一个对象(一个名为 的类)。Document
这是控制器:
[HttpPost]
public async Task<IActionResult> Post(IFormFile file, [FromForm] Document document, CancellationToken token = default)
{
...
}
Run Code Online (Sandbox Code Playgroud)
这就是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>();
}
Run Code Online (Sandbox Code Playgroud)
这是POST向所述控制器提供数据的代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,当我发送 POST 请求时,控制器中参数IFormFile的 和 属性都会被填充。[FromForm] Document只是,我对如何填充Metadata的属性一无所知Document?我怎样才能传入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);
Run Code Online (Sandbox Code Playgroud)
然后
multipartContent.Add(new StringContent(json ), FormDataKeys.Metadata );
Run Code Online (Sandbox Code Playgroud)
要反序列化它,您可以使用如下内容:
var d = JsonConvert.DeserializeObject<Dictionary<String,String>>(json, settings);
Run Code Online (Sandbox Code Playgroud)
另一种选择是子类化 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3141 次 |
| 最近记录: |