如何从C#客户端向Web API发送含IFormFile的模型类数据?
解决C#客户端向ASP.NET Core API上传包含IFormFile的模型问题
你之前使用的FormUrlEncodedContent仅支持纯文本键值对,无法处理文件上传场景。要发送包含IFormFile的模型,必须使用multipart/form-data格式,对应.NET中的MultipartFormDataContent类。
正确的客户端实现代码
using (var content = new MultipartFormDataContent()) { // 添加普通文本参数,参数名需与API模型中的属性名一致 content.Add(new StringContent(model.empName), "empName"); content.Add(new StringContent(model.location), "location"); // 处理IFormFile类型的文件参数 if (model.imageFile != null && model.imageFile.Length > 0) { // 将文件流包装为StreamContent var fileContent = new StreamContent(model.imageFile.OpenReadStream()); // 设置文件的Content-Type,直接复用文件自带的类型即可 fileContent.Headers.ContentType = new MediaTypeHeaderValue(model.imageFile.ContentType); // 添加到multipart内容中:参数名要和API模型的imageFile匹配,同时指定文件名 content.Add(fileContent, "imageFile", model.imageFile.FileName); } // 发送POST请求到API var response = await _httpClient.PostAsync(baseUrl, content); // 可选:确保请求成功,失败时抛出异常 response.EnsureSuccessStatusCode(); }
注意事项
- 你的API端代码无需修改,
[FromForm]特性已经正确指定了接收form-data格式的请求 - 若客户端的文件不是来自
IFormFile(比如本地文件),可以直接读取文件流创建StreamContent:var localFileStream = File.OpenRead(@"C:\example.jpg"); var fileContent = new StreamContent(localFileStream); fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); content.Add(fileContent, "imageFile", "example.jpg"); - 注意修正你原代码中的错误:第三个键值对的参数名应该是
imageFile而非location
内容的提问来源于stack exchange,提问作者Talha Mahmood
相关产品推荐
相关产品推荐

