在HTTP中有两种POST数据的方式:application/x-www-form-urlencoded和multipart/form-data.据我所知,大多数浏览器只能在使用时上传文件multipart/form-data.在API上下文中使用其中一种编码类型时是否有任何其他指导(不涉及浏览器)?这可能基于:
到目前为止,我基本上没有在网上找到有关使用不同内容类型的正式指导.
测试用于文件上载的Web API,有一个像这样的简单视图模型:
public class TestModel {
public string UserId {get;set;}
public HttpPostedFileBase ImageFile {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
用于方法:
[HttpPost]
public void Create(TestModel model)
Run Code Online (Sandbox Code Playgroud)
当我尝试将多部分/表单数据编码的表单发布到操作时,我收到此异常:
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 …Run Code Online (Sandbox Code Playgroud)