asp.net-mvc - Web API 模型绑定(bind)器不适用于 HttpPostedFileBase?

标签 asp.net-mvc asp.net-web-api

测试用于文件上传的 Web API,有一个像这样的简单 View 模型:

public class TestModel {
    public string UserId {get;set;}
    public HttpPostedFileBase ImageFile {get;set;}
}

使用方法:

[HttpPost]
public void Create(TestModel model)

当我尝试将多部分/表单数据编码表单发布到操作时,我收到此异常:

System.InvalidOperationException: No MediaTypeFormatter is available to read an object of type 'TestModel' from content with media type 'multipart/form-data'.
   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
   at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
   at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
   at System.Web.Http.Controllers.HttpActionBinding.<>c__DisplayClass1.<ExecuteBindingAsync>b__0(HttpParameterBinding parameterBinder)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator`1 enumerator, CancellationToken cancellationToken) 

这适用于默认的 MVC 模型绑定(bind)器,但显然不适用于 Web API。发现一些提到您在上传文件时不能使用 View 模型,并且只能将数据分成两个调用。这对我不起作用,因为我需要发布其他字段才能实际对上传的文件执行某些操作。有办法实现吗?

最佳答案

您可以编写自定义 MediaTypeFormatter 来简化您的场景,也可以使用 MultipartFormDataStreamProvider.FormData.AllKeys 集合手动从请求中提取数据。这样您就可以在一个请求中同时发布文件和附加字段。

Mike Wasson 提供的一个很好的教程可以在这里找到: http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2

关于asp.net-mvc - Web API 模型绑定(bind)器不适用于 HttpPostedFileBase?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12697310/

相关文章:

c# - 如何反序列化此 JSON?

angular - 如何使用 msbuild 从 dotnetcore web-api 项目中触发 "ng build",但将 Angular 项目保存在单独的文件夹中?

c# - 奇怪的错误 : The type name 'Models' does not exist in the type . ... 播种实体数据库时

asp.net-mvc - 如何获取Controller中ActionResult返回的html

c# - 如何通过 Web API 跟踪断开连接的实体

c# - 在项目扩展中使用 Msbuild 变量

asp.net-mvc - Post 方法在 Asp.net 核心 Web API Controller 中返回 404

asp.net-mvc - 将 MVC 操作限制为 contentType

android - mvc Controller 中重定向到 'market://details?id=my.package.name' 失败

css - 在 MVC 元素中隐藏鼠标悬停的超链接