4.24Setting the Form Name Policy (Transformer)
When sending HTTP form data, unlike directly sending JSON data in application/json format, you cannot directly use custom JSON serialization options to format property names. When setting an object as form data, the framework first converts the object to the IDictionary<string, object?> type and then adds it item by item as form fields. Therefore, this process does not follow the naming rules of JSON serialization.
Because properties in the C# language are typically named using PascalCase naming, when interacting with some third-party services (such as APIs written in Java), the other party may be case-sensitive about field names, causing the request to fail. For this reason, the framework provides the SetFormNameTransformer method for configuring the transformation rules for form field names.
HttpRequestBuilder.Post("https://furion.net") .SetMultipartContent(multipart => { multipart.AddObject(new { Id = 1, Name = "Furion"}) .SetFormNameTransformer(FormNamingPolicy.CamelCase); // Use camelCase naming to transform form field names });The framework has built in the following five common naming-rule transformation approaches, and it also supports custom transformation logic:
- camelCase naming (
FormNamingPolicy.CamelCase): for example, transformsTempCelsiusintotempCelsius. - lowercase snake_case naming (
FormNamingPolicy.SnakeCaseLower): for example, transformsTempCelsiusintotemp_celsius. - uppercase snake_case naming (
FormNamingPolicy.SnakeCaseUpper): for example, transformsTempCelsiusintoTEMP_CELSIUS. - lowercase kebab-case naming (
FormNamingPolicy.KebabCaseLower): for example, transformsTempCelsiusintotemp-celsius. - uppercase kebab-case naming (
FormNamingPolicy.KebabCaseUpper): for example, transformsTempCelsiusintoTEMP-CELSIUS.
In addition, you can implement a specific format through a custom transformer delegate, for example uniformly adding a _ prefix to all field names:
HttpRequestBuilder.Post("https://furion.net") .SetMultipartContent(multipart => { multipart.AddObject(new { Id = 1, Name = "Furion"}) .SetFormNameTransformer(name => "_" + name); });