如何使用RestSharp向Freshdesk outbound_email API发送字符串数组标签参数?
在RestSharp中为Freshdesk Outbound Email API添加标签数组参数
直接用AddParameter传数组或者手动转JSON字符串都不行——前者会把数组解析为form-data格式,后者容易导致参数类型不匹配。正确的做法是让RestSharp自动处理JSON序列化,以下是两种可行方案:
方案1:使用AddJsonBody(推荐)
AddJsonBody会自动将对象序列化为JSON格式,并设置正确的Content-Type请求头,完美适配Freshdesk API对JSON数组的要求:
var client = new RestClient("https://your-domain.freshdesk.com/api/v2/outbound_emails"); var request = new RestRequest(Method.POST); // 配置认证头(替换为你的API密钥) request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("your-api-key:x"))); // 构造包含tags数组的请求体(补充其他必填字段,比如subject、to_email等) var emailPayload = new { subject = "Support Follow-Up", to_email = "customer@example.com", body = "Please let us know if you need further assistance.", tags = new string[] { "follow-up", "priority-low", "support-ticket" } }; // 自动序列化并添加请求体 request.AddJsonBody(emailPayload); var response = client.Execute(request);
方案2:使用AddObject配合JSON格式设置
如果习惯用AddObject,需要显式指定请求格式为JSON,确保RestSharp正确序列化数组:
var client = new RestClient("https://your-domain.freshdesk.com/api/v2/outbound_emails"); var request = new RestRequest(Method.POST); request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("your-api-key:x"))); // 显式设置请求格式为JSON request.RequestFormat = DataFormat.Json; var emailPayload = new { subject = "Welcome Email", to_email = "new-user@example.com", body = "Thanks for signing up!", tags = new[] { "onboarding", "welcome" } }; request.AddObject(emailPayload); var response = client.Execute(request);
关键注意事项
- 不要手动将
tags数组转为JSON字符串后用AddParameter传递,这会导致Freshdesk API收到的是字符串类型而非数组,触发参数校验失败 - 确保所有Freshdesk API要求的必填字段都已包含在请求体中,缺失必填字段也会导致接口拒绝请求
- 认证头的格式必须正确:API密钥后要加
:x,再转Base64
内容的提问来源于stack exchange,提问作者James Wilson
相关产品推荐
相关产品推荐

