我的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#代码将数据类中的值传递到这个方法中。我需要传递字符串A、两个字符串数组B和C以及文件文件。我可以通过Swagger轻松地做到这一点,但不能通过代码。我有api的URL,所以这不是问题。唯一的问题是知道在这里编写什么代码。
发布于 2019-11-01 06:30:49
尝试在控制器中使用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);
}
}https://stackoverflow.com/questions/58645233
复制相似问题