Testing out Web API for file uploading, have a simple view model like this:
public class TestModel {
public string UserId {get;set;}
public HttpPostedFileBase ImageFile {get;set;}
}
Used in the method:
[HttpPost]
public void Create(TestModel model)
When I attempt to post a multipart/form-data encoded form to the action, I receive this exception:
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)
This works with the default MVC model binder, but apparently not with Web API's. Found some mentions that you can't use a view model when uploading a file, and to just separate the data into two calls. That doesn't work for me, since I need the other fields being posted in order to actually do something with the uploaded file. Is there a way to accomplish this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…