【发布时间】:2016-01-07 06:00:56
【问题描述】:
测试用于文件上传的 Web API,有一个像这样的简单视图模型:
public class TestModel {
public string UserId {get;set;}
public HttpPostedFileBase ImageFile {get;set;}
}
在方法中使用:
[HttpPost]
public void Create(TestModel model)
当我尝试将 multipart/form-data 编码的表单发布到操作时,我收到此异常:
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 模型绑定器,但显然不适用于 Web API。发现一些提到上传文件时不能使用视图模型,并且只是将数据分成两个调用。这对我不起作用,因为我需要发布其他字段才能对上传的文件进行实际操作。有没有办法做到这一点?
【问题讨论】:
-
您需要编写一个自定义的
MediaTypeFormatter才能使其工作。正如您所经历的那样,开箱即用不支持“multipart/form-data”。你可以开始here
标签: asp.net-mvc asp.net-web-api