如何在RestSharp的multipart/form-data请求中为参数指定ContentType
解决RestSharp发送带指定Content-Type的multipart/form-data请求问题
要实现Postman中那种为单个参数指定application/json Content-Type的multipart请求,你需要调整参数的添加方式,直接为request参数设置Content-Type属性,而非嵌套传递参数。以下是修正后的代码:
var request = new RestRequest("/sendDocument") { AlwaysMultipartFormData = true }; // 将请求对象序列化为JSON字符串 var requestJson = JsonConvert.SerializeObject(sendDocRequestObjectRequest); // 创建request参数并显式指定Content-Type var requestParam = new Parameter { Name = "request", Value = requestJson, Type = ParameterType.GetOrPost, ContentType = "application/json" }; request.AddParameter(requestParam); request.AddFile("files", @"c:\test.pdf"); var response = restClient.Post(request);
关键说明:
- 先将
sendDocRequestObjectRequest对象序列化为JSON字符串(示例使用Newtonsoft.Json,也可使用RestSharp自带序列化工具)。 - 手动创建
Parameter对象并设置ContentType,确保该参数在multipart请求中携带application/json头。 - 原代码中嵌套添加参数的方式错误,会导致参数对象被当作值传递,而非正确的表单参数。
如果使用RestSharp v107及以上版本,可使用更简洁的重载写法:
var request = new RestRequest("/sendDocument").AddMultipartFormData(); // 直接添加带指定参数名和Content-Type的JSON内容 request.AddStringBody(JsonConvert.SerializeObject(sendDocRequestObjectRequest), ContentType.Json, "request"); request.AddFile("files", @"c:\test.pdf"); var response = restClient.Post(request);
这里AddStringBody的第三个参数指定了multipart表单中的参数名request,同时通过ContentType.Json设置该部分的Content-Type。
内容的提问来源于stack exchange,提问作者Orpheos
相关产品推荐
相关产品推荐

