测试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”不支持开箱即用。你可以从这里开始:http://lonetechie.com/2012/09/23/web-api-generic-mediatypeformatter-for-file-upload/ - nemesv