简体   繁体   中英

How can I accept parameters in this post web api method(non-async)?

I am trying to figure out how to make my webapi post operation to accept params with file upload at the same time (multipart for data)

thanks

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";
}

Try accessing HttpRequest.Form . It is of type NameValueCollection and will contain form data passed through the Http request.

You can't have parameters on a Multipart/Form-Data request. What you need to do is pass in the parameters in the body of the request and parse them out. There are examples of how to do this here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2#reading-form-control-data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM