测试用于文件上传的 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/