该模型:
public class UploadFileModel { public int Id { get; set; } public string FileName { get; set; } public HttpPostedFileBase File { get; set; } }
控制器:
public void Post(UploadFileModel model) { // never arrives... }
我收到了一个错误
“No MediaTypeFormatter is available to read an object of type ‘UploadFileModel’ from content with media type ‘multipart/form-data’.”
有没有办法解决?
解决方法
这不容易. Web API中的模型绑定与MVC根本不同,您必须编写一个MediaTypeFormatter,它将文件流读入您的模型,并另外绑定可能相当具有挑战性的原语.
最简单的解决方案是使用某种类型的MultipartStreamProvider从请求中获取文件流,并使用该提供程序使用FormData名称值集合的其他参数
示例 – http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2:
public async Task<HttpResponseMessage> PostFormData() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); try { await Request.Content.ReadAsMultipartAsync(provider); // Show all the key-value pairs. foreach (var key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(key)) { Trace.WriteLine(string.Format("{0}: {1}",key,val)); } } return Request.CreateResponse(HttpStatusCode.OK); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,e); } }