【问题标题】:is it possible to have modelbinding in asp.net webapi with uploaded file?是否可以在带有上传文件的 asp.net web api 中进行模型绑定?
【发布时间】:2012-10-15 18:39:28
【问题描述】:

型号:

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’类型的对象。”

还有这个问题吗?

【问题讨论】:

标签: c# asp.net-web-api file-upload model-binding


【解决方案1】:

这不是容易可能的。 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);
    }
}

【讨论】:

    猜你喜欢
    • 2016-09-16
    • 2021-11-23
    • 2012-09-27
    • 2012-10-23
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    相关资源
    最近更新 更多