使用C# HttpClient发送MultipartFormDataContent传递整数值失败求助
问题:HttpClient替代RestClient调用Freshservice API时工单参数异常
测试Freshservice API时,RestClient能成功创建工单,但该组件会引入约20个额外依赖,因此希望改用HttpClient实现。目前HttpClient代码无法生成符合预期的工单,怀疑是status和priority参数传递问题,需要修复。
可正常运行的RestClient代码
var options = new RestClientOptions(_freshdeskUrl) { Authenticator = new HttpBasicAuthenticator(apiKey, "X") }; var client = new RestClient(options); var request = new RestRequest("", Method.Post); request.AddHeader("Accept", "application/json"); request.AddHeader("Content-Type", "multipart/form-data"); request.AddParameter("email", "tom@outerspace.com"); request.AddParameter("subject", "panel can't see files"); request.AddParameter("description", "confirm whether received"); request.AddParameter("name", "Name"); request.AddParameter("status", "2"); request.AddParameter("priority", "1"); var response = client.Execute(request); Console.WriteLine(response);
无法正常工作的HttpClient代码
HttpClient httpClient = new HttpClient(); string authInfo = apiKey + ":X"; var byteArray = new UTF8Encoding().GetBytes(authInfo); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); MultipartFormDataContent form = new MultipartFormDataContent(); form.Add(new StringContent("panel can't see files"), "username"); form.Add(new StringContent("tom@outerspace.com"), "email"); form.Add(new StringContent("confirm whether received"), "description"); form.Add(new StringContent("2"), "status"); form.Add(new StringContent("1"), "priority"); HttpResponseMessage response = await httpClient.PostAsync(_freshdeskUrl, form); //response.EnsureSuccessStatusCode(); httpClient.Dispose();
服务器返回响应
StatusCode: 201, ReasonPhrase: 'Created', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers: { Date: Wed, 09 Oct 2024 14:05:36 GMT Transfer-Encoding: chunked Connection: keep-alive Status: 201 Created Cache-Control: no-store Strict-Transport-Security: max-age=63072000; includeSubDomains X-Freshservice-Api-Version: latest=v2; requested=v2 Pragma: no-cache X-Request-ID: b27d2c81-78c7-96af-8f5e-5c24fbecc271 Location: https://nccnusersupport.freshservice.com/api/v2/tickets/21027178338 X-Envoy-Upstream-Service-Time: 321 X-Fw-Ratelimiting-Managed: true X-Ratelimit-Total: 140 X-Ratelimit-Remaining: 139 X-Ratelimit-Used-Currentrequest: 1 X-Trace-Id: 00-da1535c2223299d7d3040faac49b8719-e0b5e2503d7f2fb5-01 Nel: { "report_to": "nel-endpoint-freshservice", "max_age": 2592000, "include_subdomains": true} Report-To: { "group": "nel-endpoint-freshservice", "max_age": 2592000, "include_subdomains": true, "endpoints": [{"url": "https://edge-admin.us-east-1.freshedge.net/nelreports/freshservice"}]} Server: fwe Content-Type: application/json; charset=utf-8 Expires: Wed, 13 Oct 2010 00:00:00 UTC }}
修复方案
你的HttpClient代码有两个关键错误,和status、priority的类型无关(API接受字符串形式的数字参数,RestClient也是这么传的):
- 参数名错误:把
subject参数写成了username,导致工单主题丢失 - 缺失必要参数:没有添加
name参数,这是RestClient里包含的重要参数
修复后的HttpClient代码如下:
HttpClient httpClient = new HttpClient(); string authInfo = apiKey + ":X"; var byteArray = new UTF8Encoding().GetBytes(authInfo); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); // 添加Accept头,和RestClient保持一致 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); MultipartFormDataContent form = new MultipartFormDataContent(); // 修正参数名:把username改为subject form.Add(new StringContent("panel can't see files"), "subject"); form.Add(new StringContent("tom@outerspace.com"), "email"); form.Add(new StringContent("confirm whether received"), "description"); // 添加缺失的name参数 form.Add(new StringContent("Name"), "name"); form.Add(new StringContent("2"), "status"); form.Add(new StringContent("1"), "priority"); HttpResponseMessage response = await httpClient.PostAsync(_freshdeskUrl, form); // 可以取消注释来验证响应状态 // response.EnsureSuccessStatusCode(); httpClient.Dispose();
额外优化建议:
- 不要每次创建HttpClient都Dispose,推荐复用单例HttpClient以避免socket资源耗尽
- 可以读取响应内容确认工单参数是否正确:
var responseContent = await response.Content.ReadAsStringAsync();
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

