简体   繁体   中英

Upload file from WinForms to .Net Core 3.1 API

This code has been working for 6 months on .Net Core 2.2, but no longer works when we "upgraded" to .Net Core 3.1. The file is received on the server, but the other parameters are always null.

Client Code:

    public async Task<bool> UploadFile(string sourcePath, string destinationPath, bool createPath, bool overwriteFile)
    {
        bool status = false;

        try
        {
            MultipartFormDataContent multipart = new MultipartFormDataContent();
            multipart.Add(new StringContent(destinationPath), "destinationPath");
            multipart.Add(new StringContent(createPath.ToString()), "createPath");
            multipart.Add(new StringContent(overwriteFile.ToString()), "overwriteFile");
            multipart.Add(new ByteArrayContent(File.ReadAllBytes(sourcePath)), "files", "files");

            // Select the API to call
            string path = $"UploadFile/{multipart}";

            // Make request and get response
            HttpResponseMessage response = await restClient.PostAsync(path, multipart);
            if (response.IsSuccessStatusCode)
            {
                string jsonResult = await response.Content.ReadAsStringAsync();
                if (jsonResult.Contains("true"))
                    status = true;
            }
        }
        catch (Exception ex)
        {
            appLog.WriteError(ex.Message);
        }

API Code:

    [HttpPost("UploadFile/{multipart}", Name = "UploadFile")]
    [RequestSizeLimit(40000000)] // Max body size (upload file size)
    public async Task<ActionResult<bool>> UploadFile(List<IFormFile> files, string destinationPath, bool createPath, bool overwriteFile)

    {
        // server side code here
    }

No obvious errors on the console. All the other APIs work fine, just this one that utilizes MultipartFormDataContent code no longer works properly.

I'm pretty sure multiple parameters like that is not allowed any longer. Luckily it's usually pretty smart about figuring out the object.

Instead of passing multiple parameters, replace the parameters with an object with properties that match the existing parameters. It should work without changes to the client.

public class PostBodyMessage
{
 public List<IFormFile> files {get; set;}
 public string destinationPath {get; set;}
 public bool createPath {get; set;}
 public bool overwriteFile {get; set;}
}

[HttpPost("UploadFile/{multipart}", Name = "UploadFile")]
[RequestSizeLimit(40000000)] // Max body size (upload file size)
public async Task<ActionResult<bool>> UploadFile(PostBodyMessage message)

{
    // server side code here
}

This should work.

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