【问题标题】:Asp.net WebApi 2 File upload with Model ObjectAsp.net WebApi 2 使用模型对象上传文件
【发布时间】:2019-02-10 19:26:49
【问题描述】:

项目是(Azure 上的 .net Framework 4.6.1) 有谁知道是否有办法使用控制器在同一个请求中同时接受文件上传和模型实体(Json)。客户端应用程序需要上传文件以及有关文件的元数据,如果可能,我们希望在一个请求中完成。

我想到了两种可能:

  1. 发布文件和各个模型字段(模型是平面的),就好像它是一个 Web 表单一样,因此请从表单中手动构建我的模型对象。 (拉https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2
  2. 将文件和模型对象作为另一个 json 文件发布,并作为自定义 MultipartMemoryStreamProvider 的一部分反序列化到我的模型对象中

我错过了一个选项吗? TIA

【问题讨论】:

  • 根据您的元数据中有多少字段,您可以将自定义标头添加到您的请求中,作为选项 3。

标签: c# asp.net .net asp.net-web-api2


【解决方案1】:

我想尝试的只是将文件添加到模型中,或者创建一个包含数据和文件的 ViewModel。由于数据绑定,只要您在客户端的输入字段名称相同,那么在请求期间该数据将映射到对象。

型号:

public class yourModel
{
    public string name {get;set;}
    ...
    //other data

    public IFormFile yourFile {get;set;} //your file
    ...
}

控制器:

[Route("YourRoute")]
[HttpPost]
public async Task<WhateverYouWantToReturn> YourAction(yourModel model)
{
     //set a breakpoint here to see if your fields populated
     ...
     //do something with your model
     ...
     return WhateverYouWantToReturn;
}

查看: 只要输入字段的名称与对象中字段的名称匹配,它们就应该映射。

<form enctype="multipart/formdata" method="post" action="/your/route">
     <input type="text" name="name"/>
     <input type="hidden" name="somesHiddenField" value="yourValue" />
     ... <!-- Whatever other fields you need. -->
     <input type="file" name="yourFile"/>
     <input type="submit" value="Submit" />
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 2013-06-23
    • 2013-11-10
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    相关资源
    最近更新 更多