IHttpContentSerializer make ToHttpContent async #2010
Replies: 1 comment 1 reply
-
|
You do not actually need sealed class EncryptingContent<T>(T item, IHttpContentSerializer inner) : HttpContent
{
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context)
{
// you still have the typed model here
using var plain = inner.ToHttpContent(item);
var bytes = await plain.ReadAsByteArrayAsync().ConfigureAwait(false);
var encrypted = await EncryptAsync(bytes).ConfigureAwait(false);
await stream.WriteAsync(encrypted).ConfigureAwait(false);
}
protected override bool TryComputeLength(out long length) { length = -1; return false; }
}
public sealed class EncryptingSerializer(IHttpContentSerializer inner) : IHttpContentSerializer
{
public HttpContent ToHttpContent<T>(T item) => new EncryptingContent<T>(item, inner);
public Task<T?> FromHttpContentAsync<T>(HttpContent content, CancellationToken ct = default)
=> inner.FromHttpContentAsync<T>(content, ct);
public string? GetFieldNameForProperty(PropertyInfo p) => inner.GetFieldNameForProperty(p);
}Wire it via Leaving this open as an idea is fine, but the pattern above unblocks the encryption scenario today without an async |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
It would be useful if the ToHttpContent method could be asynchronous.
In my case, the request body type T needs to be available before I can perform an asynchronous encryption step. I initially considered using a DelegatingHandler, but at that stage, the request body has already been serialised into raw JSON, and the original type T is no longer accessible.
Having an async ToHttpContent would make it possible to work with the typed request model before it’s serialised, enabling scenarios like encryption or other async preprocessing steps.
Beta Was this translation helpful? Give feedback.
All reactions