首页 > 解决方案 > 将文件从 WinForms 上传到 .Net Core 3.1 API

问题描述

这段代码在 .Net Core 2.2 上已经运行了 6 个月,但是当我们“升级”到 .Net Core 3.1 时不再有效。文件在服务器上接收,但其他参数始终为空。

客户代码:

    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 代码:

    [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
    }

控制台上没有明显的错误。所有其他 API 都可以正常工作,只是这个使用 MultipartFormDataContent 代码的 API 不再正常工作。

标签: c#.net

解决方案


我很确定不再允许这样的多个参数。幸运的是,找出对象通常非常聪明。

不要传递多个参数,而是将参数替换为具有与现有参数匹配的属性的对象。它应该可以在不更改客户端的情况下工作。

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
}

这应该有效。


推荐阅读