我的 WebApi 有以下方法
[HttpPost]
[Route("foo/bar")]
[Consumes("multipart/form-data")]
[DisableRequestSizeLimit]
public async Task<IActionResult> FooBar([FromForm] 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,所以这不是问题。唯一的问题是知道在这里编写什么代码。
尝试使用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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)