.NET Core 6控制台如何向含IFormFile属性的上传API传递模型参数
.NET 6 客户端调用文件上传接口实现
你的接口使用[FromForm]特性接收参数,本质是接收multipart/form-data编码的HTTP请求,客户端不需要构造IFormFile类型实例。IFormFile是ASP.NET Core服务端专属的模型绑定类型,用来映射请求中上传的文件内容,客户端只需要按照表单上传的规范提交文件和其他字段,服务端就会自动完成模型绑定。
下面分别提供原生HttpClient和RestSharp两种实现方式:
方式一:原生HttpClient实现(无第三方依赖)
HttpClient建议在应用生命周期内单例复用,不要每次请求都新建实例,避免socket资源耗尽。
using System.Net.Http.Headers; // 全局初始化一次即可 var httpClient = new HttpClient(); var requestUri = "http://你的接口服务地址/addDocument"; // 读取本地待上传文件 var localFilePath = @"C:\Files\demo.docx"; var fileName = Path.GetFileName(localFilePath); // 构造multipart表单容器 using var formData = new MultipartFormDataContent(); // 添加上传文件字段,字段名必须和模型[JsonPropertyName]指定的"file"完全一致 await using var fileStream = File.OpenRead(localFilePath); var fileContent = new StreamContent(fileStream); // 根据实际文件类型设置MIME,比如docx对应application/vnd.openxmlformats-officedocument.wordprocessingml.document fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); formData.Add(fileContent, "file", fileName); // 添加其余业务表单字段,字段名和模型配置的JsonPropertyName一一对应 formData.Add(new StringContent("test-user-001"), "userId"); formData.Add(new StringContent("测试文档"), "title"); formData.Add(new StringContent("1.0.0"), "version"); // 发送请求 var response = await httpClient.PostAsync(requestUri, formData); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"请求成功,返回结果:{responseContent}");
小文件场景也可以一次性读取字节数组用ByteArrayContent提交,大文件优先用上面的StreamContent流式上传,降低内存占用。
方式二:RestSharp实现
先通过NuGet安装RestSharp包,RestSharp封装了表单上传的细节,代码更简洁:
using RestSharp; // 全局初始化一次即可 var restClient = new RestClient("http://你的接口服务地址/"); var request = new RestRequest("addDocument", Method.Post); // 添加文件,第一个参数为接口绑定的字段名"file" request.AddFile("file", @"C:\Files\demo.docx"); // 添加其余业务字段 request.AddParameter("userId", "test-user-001"); request.AddParameter("title", "测试文档"); request.AddParameter("version", "1.0.0"); // 执行请求 var response = await restClient.ExecuteAsync(request); if (response.IsSuccessful) { Console.WriteLine($"请求成功,返回结果:{response.Content}"); } else { Console.WriteLine($"请求失败,状态码:{response.StatusCode},错误信息:{response.ErrorMessage}"); }
额外注意:你贴出的服务端代码中
GetBlobClient(model.DocumentPath)使用的DocumentPath属性并未在DocumentModel类中定义,会触发编译错误,记得补充该字段或自行实现Blob存储路径的生成逻辑。
内容的提问来源于stack exchange,提问作者mnu-nasir
相关产品推荐
相关产品推荐

