如何接受此帖子后api方法中的参数(非异步)?

时间:2017-07-13 22:58:58

标签: c# asp.net-web-api

我想弄清楚如何让我的webapi post操作同时接受带文件上传的params(数据的多部分)

感谢

public string Post()
{
    try
    {
        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count < 1)
        {
            return "n";
        }

        foreach (string file in httpRequest.Files)
        {
            string downloadedImagesPath = ConfigurationManager.AppSettings["DownloadedImagesPath"];

            var postedFile = httpRequest.Files[file];

            var filePath = HttpContext.Current.Server.MapPath(Path.Combine(downloadedImagesPath, postedFile.FileName));
            postedFile.SaveAs(filePath);
        }
    }
    catch (Exception ex)
    {
        return "e";
    }

    return "k";
}

2 个答案:

答案 0 :(得分:0)

尝试访问 HttpRequest.Form 。它的类型为 NameValueCollection ,并且将包含通过Http请求传递的表单数据。

答案 1 :(得分:0)

您不能在Multipart / Form-Data请求中拥有参数。您需要做的是传递请求正文中的参数并解析它们。这里有一些如何做到这一点的例子: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2#reading-form-control-data