10

该模型:

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...
}

我收到一个错误

“没有 MediaTypeFormatter 可用于从媒体类型为‘multipart/form-data’的内容中读取‘UploadFileModel’类型的对象。”

有没有办法解决?

4

1 回答 1

9

这不容易。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);
    }
}
于 2012-10-15T20:05:25.080 回答