【发布时间】:2019-03-13 07:56:12
【问题描述】:
我为附件创建了 API 它应该接收带有文件的模型信息 如果我发送文件模型为空如果我没有发送文件模型数据显示
型号
public class AttachmentFilesViewModel
{
public long Id { get; set; }
public string FileName { get; set; }
public string FileExt { get; set; }
public IFormFile files { get; set; }
public AttachmentViewModel AttachmentViewModel {get;set; }
}
模型 2
public class AttachmentViewModel
{
public long Id { get; set; }
public string Type { get; set; }
public long TypeID { get; set; }
public string FileDesc { get; set; }
public List<AttachmentFilesViewModel> attachmentFiles {get;set; }
}
控制器从视图中获取文件正确 在这里,我从文件中构建了我的 Viewmodel 文件是正确的
[HttpPost]
public async Task<IActionResult> Create(AttachmentViewModel attachment, IFormFile[] Files)
{
LawyerAPI lawyerAPI = new LawyerAPI();
HttpClient httpClient = lawyerAPI.InitializeClient();
if (Files != null && Files.Count() > 0)
{
attachment.attachmentFiles = new List<AttachmentFilesViewModel>();
foreach (var item in Files)
{
AttachmentFilesViewModel att = new AttachmentFilesViewModel();
att.FileExt = Path.GetExtension(item.FileName);
att.FileName = item.FileName;
att.files = item;
attachment.attachmentFiles.Add(att);
}
}
HttpResponseMessage res = await httpClient.PostAsJsonAsync("api/nofactory/createattachment", attachment);
List<AttachmentViewModel> model = new List<AttachmentViewModel>();
model.Add(attachment);
return View("index", model);
}
我也试过手动序列化
如果我将文件添加到模型中,这里的 API 我会收到 null 如果我评论上面的 foreach 并且文件列表为空 我收到正确的型号 我也试过 [FromBody]
[Route("createattachment")]
// POST api/values
public IActionResult Post([FromForm] AttachmentViewModel attachment)
{}
如何将文件获取到 API 谢谢
编辑
查看代码
@using (Html.BeginForm(null, null, FormMethod.Post, new { @id ="frmAddAttachment" ,enctype="multipart/form-data"})){@Html.HiddenFor(model => model.Type)@Html.HiddenFor(model => model.TypeID)<div class="row">
<div class="card">
<div class="card-content">
<div class="form-horizontal">
<div class="col-md-10 col-sm-12 col-xs-12">
<div class="form-group">
@Html.TextBoxFor(b => b.FileDesc})
</div>
</div>
<div class="col-md-10 col-sm-12 col-xs-12">
<input type="file" name="Files" multiple="multiple" />
<button type="submit" class="btn btn-success"> Save</button>
</div>
</div>
</div>
</div>
我觉得风景还可以 我确实在控制器中获取了文件,但是将它们发送到 API 时出现问题
【问题讨论】:
-
视图是什么样的?
-
我已经添加了视图的代码,但我确实从视图中获取了正确的文件,但我无法将它们发送到 API
标签: c# asp.net-core