两个服务间想传递文件数据,需要使用 MultipartFormDataContent 来模拟表单提交。其他形式基本都是 415 错误码,例如直接传递StreamContent。
Client Code
public async Task ClientUpload(){ var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = delegate { return true; }; HttpClient httpClient = new HttpClient(handler); var m = new MultipartFormDataContent(); var file=new FileInfo("test-File.json"); m.Add(new StreamContent(file.OpenRead()), name: "test", fileName: file.Name); // 这里的name需要和service 函数的参数名一致,否则无法参数获取 httpClient.BaseAddress = new Uri("service-host-url"); var response = await httpClient.PostAsync("/file/ServiceUpload", m); var content = await response.Content.ReadAsStringAsync(); }
Service Code
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.ComTypes; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace Service.Controllers { [Route("[controller]")] public class FileController : ControllerBase { [HttpPost("ServiceUpload")] public int Upload( Microsoft.AspNetCore.Http.IFormFile file) { var fileName = file.FileName; return 1; } } }