如何在C#中通过HTTPS POST发送含指定JSON的multipart/form-data到Web服务地址
在C#中发送包含指定JSON的multipart/form-data POST请求
嘿,这个需求我之前做过,用.NET自带的HttpClient就能轻松搞定!下面分两种常见的.NET环境给你提供实现代码,还有关键的注意事项:
现代.NET(.NET Core/.NET 5+)实现方案
这是目前推荐的写法,用System.Text.Json来序列化JSON,不需要额外安装第三方包:
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Threading.Tasks; class JsonMultipartSender { static async Task Main(string[] args) { // 替换成你的实际Web服务地址 var targetApiUrl = "https://your-service-endpoint.com/upload"; // 构建要发送的JSON数据对象 var infoObject = new { fullname = "Name sername", code = "123465", code2 = "12346", code3 = "1234567" }; // 将对象序列化为JSON字符串 var jsonString = JsonSerializer.Serialize(infoObject); // 构建multipart/form-data请求内容 using var multipartContent = new MultipartFormDataContent(); // 把JSON字符串作为名为"info"的表单字段添加进去,指定媒体类型为application/json multipartContent.Add( new StringContent(jsonString, System.Text.Encoding.UTF8, "application/json"), "info" ); // 注意:实际项目中HttpClient应该全局复用,不要每次请求都实例化! using var httpClient = new HttpClient(); try { // 发送POST请求 var response = await httpClient.PostAsync(targetApiUrl, multipartContent); // 确保请求返回成功状态码(2xx),否则抛出异常 response.EnsureSuccessStatusCode(); // 读取服务端返回的响应内容(如果需要处理的话) var responseResult = await response.Content.ReadAsStringAsync(); Console.WriteLine($"请求成功!响应内容:{responseResult}"); } catch (HttpRequestException ex) { Console.WriteLine($"请求失败:{ex.Message}"); } } }
关键注意事项:
- HttpClient复用:实际项目里千万不要每次请求都
new HttpClient(),这会导致系统socket资源耗尽。建议通过依赖注入(比如ASP.NET Core里的AddHttpClient)或者单例模式来复用实例。 - 媒体类型指定:给
StringContent指定application/json的媒体类型,能让服务端正确识别这个表单字段是JSON格式的数据。 - 异常处理:用
try-catch捕获HttpRequestException,可以处理网络故障、服务端返回错误状态码等异常情况。
.NET Framework 实现方案
如果你还在使用.NET Framework,需要用Newtonsoft.Json(也就是Json.NET)来序列化JSON,先通过NuGet安装这个包,然后用下面的代码:
using System; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using System.Threading.Tasks; class JsonMultipartSender { static async Task Main(string[] args) { var targetApiUrl = "https://your-service-endpoint.com/upload"; var infoObject = new { fullname = "Name sername", code = "123465", code2 = "12346", code3 = "1234567" }; // 用Newtonsoft.Json序列化对象 var jsonString = JsonConvert.SerializeObject(infoObject); using var multipartContent = new MultipartFormDataContent(); multipartContent.Add( new StringContent(jsonString, System.Text.Encoding.UTF8, "application/json"), "info" ); using var httpClient = new HttpClient(); try { var response = await httpClient.PostAsync(targetApiUrl, multipartContent); response.EnsureSuccessStatusCode(); var responseResult = await response.Content.ReadAsStringAsync(); Console.WriteLine($"请求成功!响应内容:{responseResult}"); } catch (HttpRequestException ex) { Console.WriteLine($"请求失败:{ex.Message}"); } } }
内容的提问来源于stack exchange,提问作者Doston
相关产品推荐
相关产品推荐

