【问题标题】:Direct model binding with Multipart formdata in asp.net web Api 2.0?在asp.net web Api 2.0中与Multipart formdata直接模型绑定?
【发布时间】:2018-01-29 11:02:48
【问题描述】:

假设我们有一个 html 表单,它可以发布带有产品名称和描述的产品图片。

产品名称 : 描述 : 图像文件

我想在不使用提供者表单数据的情况下检索“ProductName”和“Description”字段值。

Web API 控制器 --

if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

try
        {
            // Read the form data.
            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));
            }
        }
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }

我们可以轻松获取所有属性值。但是我们可以做一个如下的 web Api 函数吗:

 [HttpPost]
  public IHttpActionResult Upload(ProductInfo model){
  return Content(HttpStatusCode.OK, true);
} 

Public Class ProductInfo {
   public string ProductName{ get; set; }
   public string Description{ get; set; }
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc-4 asp.net-web-api asp.net-web-api2


    【解决方案1】:

    你可以这样尝试,只需添加IEnumerable<HttpPostedFileBase> files作为参数。 DefaultModelBinder,如果有一个多部分的表单数据会自动正确绑定到你的参数类型。

    [HttpPost]
    public IHttpActionResult Upload(ProductInfo model, 
                                    IEnumerable<HttpPostedFileBase> files)
    {
        return Content(HttpStatusCode.OK, true);
    } 
    

    【讨论】:

    • 它显示如下来自 WebAPI 控制器的错误无法将多个参数(“模型”和“文件”)绑定到请求的内容。我尝试使用通用模型但没有成功。我也通过fiddler检查过数据,看起来很完美。
    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多