以编程方式调用多部分表单方法 [英] Call A Multi-Part Form Method Programmatically

查看:67
本文介绍了以编程方式调用多部分表单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的WebApi中具有以下方法

I have the following method in my WebApi

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

Data类看起来像这样

The Data class looks like this

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的网址,所以这不是问题.唯一的问题是知道在此处编写什么代码.

I am struggling to work out how I can pass the values in the Data class into this method via C# code. I need to pass the string A, the two string arrays B and C and the file File. I can easily do this via Swagger but not through code. I have the URL to the api so that's not an issue. The only problem is knowing what code to write here.

推荐答案

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

Try to use HttpClient and send MultipartFormDataContent in controller

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);
    }
}

这篇关于以编程方式调用多部分表单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆