Flurl/RestSharp调用Freshdesk创建工单API时,Multipart请求参数附加\r\n引发400错误排查
Looks like the root cause here is that both Flurl and RestSharp were accidentally appending \r\n to your form field names when generating the multipart request. Freshdesk's API is strict about parsing field names and doesn't ignore these extra line breaks, hence the "invalid_field" errors.
Here's how to fix this for both libraries:
Flurl Solution
Instead of using AddString, use the AddPart method to explicitly construct each form field without extra formatting. This gives you full control over the field name and content:
var rs = await url.WithBasicAuth(_configuration.ApiKey, _configuration.Password) .PostMultipartAsync(mp => { // Explicitly define each form part with clean field names mp.AddPart( name: "email", content: new StringContent(ticket.Email), name: "email" ); mp.AddPart( name: "subject", content: new StringContent(ticket.Subject), name: "subject" ); mp.AddPart( name: "status", content: new StringContent(ticket.Status.ToString()), name: "status" ); mp.AddPart( name: "priority", content: new StringContent(ticket.Priority.ToString()), name: "priority" ); mp.AddPart( name: "description", content: new StringContent(ticket.Description), name: "description" ); // Add attachments later using AddFile: // mp.AddFile("attachments[]", "/path/to/attachment1.ext"); // mp.AddFile("attachments[]", "/path/to/attachment2.ext"); });
RestSharp Solution
Replace the generic AddParameter calls with AddFormParameter, which is designed specifically for multipart form data and ensures clean field names:
var request = new RestRequest("tickets", Method.Post); request.AlwaysMultipartFormData = true; // Use AddFormParameter for each field to avoid extra line breaks request.AddFormParameter("email", ticket.Email); request.AddFormParameter("description", ticket.Description); request.AddFormParameter("subject", ticket.Subject); request.AddFormParameter("status", ticket.Status.ToString()); request.AddFormParameter("priority", ticket.Priority.ToString()); // Add attachments using AddFile: // request.AddFile("attachments[]", "/path/to/attachment1.ext"); // request.AddFile("attachments[]", "/path/to/attachment2.ext"); var rs = await client.ExecuteAsync(request);
Why This Works
The original methods (AddString in Flurl, generic AddParameter in RestSharp) were adding unintended line breaks to the field names in the multipart request headers. By using the library-specific methods meant for multipart form fields, we ensure the field names are sent exactly as specified, matching the format Postman uses (which works successfully).
After making these changes, your request should return a 201 Created status just like Postman, and you'll be able to add attachments without additional issues.
内容的提问来源于stack exchange,提问作者Dariusz Woźniak

