RestSharp调用AddParameter方法如何移除参数多余引号实现正常传参?
RestSharp POST参数类型异常解决方案
问题原因
你遇到的参数异常由两个操作导致:
- 提前对
InvoiceLines做了JSON序列化,作为form参数提交后,后端直接将该字符串作为对应键的值,不会自动反序列化为数组结构 multipart/form-data类型的请求默认将所有普通字段转为字符串格式,你使用的后端解析时没有做自动类型转换,导致int类型的Term被识别为带引号的字符串
可行实现方案
完全可以通过RestSharp实现需求,优先尝试以下两种方案:
方案1:直接提交构造完成的JSON体
不需要逐个添加参数,先构造完整的请求参数对象,序列化为符合要求的JSON字符串后作为整体提交,可完全控制最终结构:
// 构造完整参数对象,包含所有字段 var requestParams = new { api_key = _options.ApiKey, controller = "invoice", action = "add", DebtorCode = newInvoice.DebtorCode, Term = newInvoice.Term, InvoiceLines = newInvoice.InvoiceLines }; // 序列化为标准JSON,不要单独序列化数组字段 string jsonBody = JsonConvert.SerializeObject(requestParams); var request = new RestRequest(Method.POST); // 不要开启AlwaysMultipartFormData // 第二个参数填后端要求的Content-Type,不接受application/json就填application/x-www-form-urlencoded即可 request.AddParameter("application/x-www-form-urlencoded", jsonBody, ParameterType.RequestBody); var response = Client.Execute(request);
方案2:按嵌套规则拆分form参数
如果后端严格要求multipart/form-data格式,不接受整块JSON提交,就按照数组索引的格式逐个添加数组字段,同时保留数值类型的原始格式:
var request = new RestRequest(Method.POST) { AlwaysMultipartFormData = true }; request.AddParameter("api_key", _options.ApiKey); request.AddParameter("controller", "invoice"); request.AddParameter("action", "add"); request.AddParameter("DebtorCode", newInvoice.DebtorCode); request.AddParameter("Term", newInvoice.Term); // 直接传int类型,不要转字符串 // 逐个添加数组元素,用索引标记对应位置 for (int i = 0; i < newInvoice.InvoiceLines.Count; i++) { var line = newInvoice.InvoiceLines[i]; request.AddParameter($"InvoiceLines[{i}].ProductCode", line.ProductCode); request.AddParameter($"InvoiceLines[{i}].Number", line.Number); } var response = Client.Execute(request);
替代方案
如果以上RestSharp方案都不满足要求,可以直接使用.NET原生HttpClient实现,对请求内容的可控性更高:
using var httpClient = new HttpClient(); var requestParams = new { api_key = _options.ApiKey, controller = "invoice", action = "add", DebtorCode = newInvoice.DebtorCode, Term = newInvoice.Term, InvoiceLines = newInvoice.InvoiceLines }; string jsonBody = JsonConvert.SerializeObject(requestParams); // 按需修改Content-Type var content = new StringContent(jsonBody, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.PostAsync("你的接口地址", content); string result = await response.Content.ReadAsStringAsync();
内容的提问来源于stack exchange,提问作者zebravis
相关产品推荐
相关产品推荐

