is it possible to have modelbinding in asp.net webapi with uploaded file?

匆匆过客 提交于 2019-12-01 03:30:32

It's not easily possible. Model binding in Web API is fundamentally different than in MVC and you would have to write a MediaTypeFormatter that would read the stream of files into your model and additionally bind primitives which can be considerably challenging.

The easiest solution is to grab the file stream off the request using some type of MultipartStreamProvider and the other parameters using FormData name value collection off that provider

Example - 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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!