【发布时间】:2020-07-20 17:25:47
【问题描述】:
我正在构建 WebAPI 和 WebApp,它们都使用 ASP.NET Core 2.1
我的 Web 应用正在尝试使用包含 IFormFile 和其他属性的 ViewModel 向 Web API 发送发布请求。我知道我必须使用 MultipartFormDataContent 来发布 IFormFile,但我不知道如何使用我的 ViewModel 来实现它,因为我的 ViewModel 有其他模型的 List。
我已经尝试在谷歌上搜索一些解决方案,但我只找到了没有 List 的简单 ViewModel 的解决方案,如下所示:
https://stackoverflow.com/a/41511354/7906006
https://stackoverflow.com/a/55424886/7906006.
有没有类似的解决方案
var multiContent = new MultipartFormDataContent();
var viewModelHttpContent= new StreamContent(viewModel);
MultiContent.Add(viewModelHttpContent, "viewModel");
var response = await client.PostAsJsonAsync("/some/url", multiContent);
所以我不必将我的属性一一添加到MultipartFormDataContent 并将其发布为json。
这是我的网络应用视图模型
public class CreateDataViewModel
{
public string PrimaryKeyNumber{ get; set; }
public List<Currency> ListOfCurrency { get; set; }
public IList<DataDetail> dataDetails { get; set; }
[DataType(DataType.Upload)]
public IFormFile Attachment { get; set; }
//And other properties like Boolean, Datetime?, string
}
这是我的网络应用控制器
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateDataViewModel viewModel)
{
//How to implement MultipartFormDataContent with my ViewModel in here ?
//My code below returns Could not create an instance of type Microsoft.AspNetCore.Http.IHeaderDictionary. Type is an interface or abstract class and cannot be instantiated. Path 'Attachment.Headers.Content-Disposition', line 1, position 723.
//It works fine if I don't upload a file
HttpResponseMessage res = await _client.PostAsJsonAsync<CreateDataViewModel>("api/data/create", viewModel);
var result = res.Content.ReadAsStringAsync().Result;
if (res.IsSuccessStatusCode)
{
TempData["FlashMessageSuccess"] = "Data have been submitted";
return RedirectToAction("Index", "Home"); ;
}
//Code for error checking
}
这是我的 Web API 控制器,它使用 CreateDataViewModel 作为参数来捕获发布响应。
[HttpPost]
[Route("[action]")]
public async Task<IActionResult> Create(CreateDataViewModel viewModel)
{
//Code to validate then save the data
}
【问题讨论】:
标签: asp.net-mvc rest api asp.net-core asp.net-web-api