以编程方式调用多部分表单方法

Call A Multi-Part Form Method Programmatically

我的 WebApi 中有以下方法

[HttpPost]
[Route("foo/bar")]
[Consumes("multipart/form-data")]
[DisableRequestSizeLimit]
public async Task<IActionResult> FooBar([FromForm] Data data)

数据 class 看起来像这样

public class Data
{
    public string A { get; set; }
    public string[] B { get; set; }
    public string[] C { get; set; }
    public IFormFile File { get; set; }
}

我正在努力研究如何通过 C# 代码将数据 class 中的值传递到此方法中。我需要传递字符串 A、两个字符串数组 B 和 C 以及文件 File。我可以通过 Swagger 而不是通过代码轻松地做到这一点。我有 URL 到 api,所以这不是问题。唯一的问题是知道在这里写什么代码。

尝试使用 HttpClient 并在控制器中发送 MultipartFormDataContent

using (var client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StringContent("testA"), "A");//string
        content.Add(new StringContent("testB"), "B");
        content.Add(new StringContent("testBB"), "B");//string[]
        content.Add(new StringContent("testC"), "C");
        content.Add(new StringContent("testCC"), "C");
        
        //replace with your own file path, below use an image in wwwroot for example
        string filePath = Path.Combine(_hostingEnvironment.WebRootPath + "\Images", "myImage.PNG");

        byte[] file = System.IO.File.ReadAllBytes(filePath);
                
        var byteArrayContent = new ByteArrayContent(file);

        content.Add(byteArrayContent, "file", "myfile.PNG");
        
        var url = "https://locahhost:5001/foo/bar";
        var result = await client.PostAsync(url, content);
    }
}