c# - 将文件从 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 不再正常工作。
解决方案
我很确定不再允许这样的多个参数。幸运的是,找出对象通常非常聪明。
不要传递多个参数,而是将参数替换为具有与现有参数匹配的属性的对象。它应该可以在不更改客户端的情况下工作。
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
}
这应该有效。
推荐阅读
- amazon-web-services - AWS CodeDeploy 问题:无法在 appspec 文件中运行挂钩
- c++ - 如何在 package.preload 函数中破坏 C++ 类
- c++11 - 使用不同持续时间(std::chrono::milliseconds 和 std::chrono::nanoseconds)创建的 time_point 是如何如此不同的
- excel - 将多列堆叠在一起,excel
- three.js - 如何使用 WebARonARKit 和 three.ar.js 进行远程测试
- java - 持久可重试任务库
- excel - 从 Excel 导入日期时间变量而不丢失 24 小时格式
- javascript - 相同的日期(字符串)给出不同的结果
- spring - 硒测试:如何绕过硒中的 okta
- php - 有没有办法使用 RDF 数据构建基于 wordpress 的 CMS