问题
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)
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; }
}
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.
回答1:
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);
}
}
来源:https://stackoverflow.com/questions/58645233/call-a-multi-part-form-method-programmatically