【问题标题】:Call A Multi-Part Form Method Programmatically以编程方式调用多部分表单方法
【发布时间】:2019-10-31 14:14:31
【问题描述】:

我的 WebApi 中有以下方法

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

Data 类如下所示

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

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

【问题讨论】:

    标签: c# asp.net-core post asp.net-web-api restsharp


    【解决方案1】:

    尝试在控制器中使用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);
        }
    }
    

    【讨论】:

    • 如果你有这种情况怎么办:API => api client => 3rdparty.. api 客户端应该如何处理Ifile?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多