7.2Using the Dynamic Object Clay to Build and Receive Request Data
The dynamic object (Clay) has a very wide range of application scenarios in HTTP remote requests, especially when integrating with third-party API interfaces. Typically, these interfaces need to pass or receive data in JSON format, and the dynamic object can simplify the process of building and parsing data. The following are the configuration steps for using the dynamic object in the HTTP remote request module:
1. Configuring the Dynamic Object JSON Serialization Converter
When using the dynamic object for HTTP remote requests, you first need to configure AddClayConverters() so that the dynamic object can be serialized into a JSON format string. A configuration example is as follows:
// Global configuration (applies to all clients)services.AddHttpRemote(options => {}) .ConfigureOptions(options => { options.JsonSerializerOptions.AddClayConverters(); });// Client-level configuration (higher priority)services.AddHttpClient("client-name") .ConfigureOptions(options => { options.JsonSerializerOptions.AddClayConverters(); });2. Sending and Receiving JSON Data
After configuration is complete, you can use the dynamic object to build the request content and send the HTTP request, and at the same time convert the response content into a dynamic object for processing. The following is an example:
// Build the request contentdynamic payload = new Clay();payload.id = 1;payload.name = "furion";// Send the HTTP remote requestvar content = await httpRemoteService.PostAsStringAsync("https://localhost:7044/HttpRemote/AddModel", builder => builder.SetJsonContent(payload));// Convert the response content into a dynamic objectdynamic clay = Clay.Parse(content);Custom Clay Content Converter Simplifies Manual Conversion ✅
To simplify the code and avoid manually converting JSON format strings into dynamic objects (such as dynamic clay = Clay.Parse(content);), you can customize the ClayContentConverter content converter. In this way, you can directly use the Clay type as a generic receiving parameter in HTTP requests. The following is the implementation of the custom converter:
【One-click download ClayContentConverter.cs file】✅
public class ClayContentConverter : HttpContentConverterBase<Clay>{ /// <inheritdoc /> public override Clay? Read(HttpContentConverterContext context, CancellationToken cancellationToken = default) => AsyncUtility.RunSync(() => ReadAsync(context, cancellationToken)); /// <inheritdoc /> public override async Task<Clay?> ReadAsync(HttpContentConverterContext context, CancellationToken cancellationToken = default) { var str = await context.ResponseMessage.Content.ReadAsStringAsync(cancellationToken); return Clay.Parse(str, ClayOptions.Flexible); // or use Clay.Parse(str, ClayOptions.Flexible); // ignore property casing }}// supports converting dynamic types to dynamic objects (optional, but recommended!!!)public class DynamicContentConverter : HttpContentConverterBase<dynamic>{ /// <inheritdoc /> public override dynamic? Read(HttpContentConverterContext context, CancellationToken cancellationToken = default) => AsyncUtility.RunSync(() => ReadAsync(context, cancellationToken)); /// <inheritdoc /> public override async Task<dynamic?> ReadAsync(HttpContentConverterContext context, CancellationToken cancellationToken = default) { var str = await context.ResponseMessage.Content.ReadAsStringAsync(cancellationToken); return Clay.Parse(str, ClayOptions.Flexible); // or use Clay.Parse(str, ClayOptions.Flexible); // ignore property casing }}Next, configure and register the HttpRemote service in the Startup.cs or Program.cs file to enable the custom content converter functionality:
services.AddHttpRemote(options =>{ options.AddHttpContentConverters(() => [ new ClayContentConverter(), new DynamicContentConverter()]); // new DynamicContentConverter() (optional, but recommended!!)});After the configuration is complete, you can directly use the dynamic object type Clay as the generic receiving parameter:
// send an HTTP remote request and convert the response content into a dynamic objectdynamic clay = await httpRemoteService.PostAsAsync<Clay>("https://localhost:7044/HttpRemote/AddModel", builder => builder.SetJsonContent(payload));// if DynamicContentConverter is configured, you can also use dynamic to receive itdynamic clay = await httpRemoteService.PostAsAsync<dynamic>("https://localhost:7044/HttpRemote/AddModel", builder => builder.SetJsonContent(payload));By combining dynamic objects with HTTP remote requests, developers can handle dynamic JSON data more efficiently and simplify the integration process with third-party APIs. The dynamic nature of dynamic objects makes data construction and parsing more flexible, while custom content converters further improve development efficiency.