loading experience

.NET

.NET 11 libraries: JSON, networking, cryptography, validation and diagnostics

What's new in .NET 11: System.Text.Json unions and JSONL, networking and TLS, X25519, ML-KEM, HPKE, async validation, MemoryCache metrics, LINQ FullJoin.

This is the second part of our tour of the .NET 11 libraries (now generally available): JSON serialization, CBOR, networking and transport security, cryptography, configuration, validation, diagnostics and LINQ. For processes, compression and numerics see the first article of the series.

System.Text.Json

Unions

Starting in .NET 11, C# offers union types, for example public union Reading(int, string);. The serializer writes the active case directly, with no wrapper or $type discriminator: "hello" for a string, 42 for an integer, null for a union with no active case. On deserialization the case is selected from the JSON token kind; to tell two object cases apart, use JsonUnionAttribute with JsonUnionTypeStructuralClassifier, which picks by root-level property names. If zero or several cases match, a JsonException is thrown. For custom rules, derive from JsonTypeClassifierFactory and register it on one union, on JsonSerializerOptions.TypeClassifiers or on a source-generated context. JsonNumberHandlingAttribute is honored on unions and the generator no longer reports SYSLIB1227 for custom converters.

F# discriminated unions are serialized as strings (cases without fields) or objects with $type; that support is reflection-only and does not work with source generation, trimming or Native AOT.

JSON Lines, polymorphism and metadata

  • JSONL: four JsonSerializer.SerializeAsyncEnumerable overloads target a Stream or PipeWriter; with topLevelValues: true they stream canonical JSON Lines (one compact value per line, LF-terminated, ignoring WriteIndented).
  • Closed hierarchies: with InferClosedTypePolymorphism (on options, the generator or JsonPolymorphicAttribute) the serializer infers derived types and assigns deterministic discriminators; explicit JsonDerivedTypeAttribute registrations take precedence. Open generic derived registrations such as Derived<> are supported too.
  • Source generation: [JsonInclude] members with private, internal or protected accessors; inaccessible constructors marked with JsonConstructorAttribute; in, ref, out and ref readonly parameters; omitted init-only properties keep their initializer value.
  • GetTypeInfo<T>() and TryGetTypeInfo<T>(): return JsonTypeInfo<T> without a cast.
  • Naming and ignoring: JsonNamingPolicy.PascalCase, JsonNamingPolicyAttribute on a type or member, JsonIgnoreAttribute with a type-level condition (Always is invalid at type level).
  • Converters and collections: built-in converters for BFloat16, Decimal32, Decimal64, Decimal128; open generic converters; JsonExtensionData on IReadOnlyDictionary; IReadOnlySet<T> as an array.
  • Utf8JsonWriter: Reset with JsonWriterOptions lets you reuse a writer.

Incremental CBOR

CborReader reads CBOR payloads delivered in chunks: construct it with isFinalBlock: false, check CborReaderState.NeedsMoreData and pass the next chunk to SlideData. It requires CborConformanceMode.Lax.

Networking and transport security

  • TLS handshake: bounds-checking fixes in server-side SslStream; on Linux, certificate-validation failures surface as standard TLS alerts as on Windows; Negotiate servers validate channel binding tokens on Unix as well.
  • Caller-driven TLS sessions (experimental): TlsContext, TlsSession, TlsBufferSession, TlsSocketSession, TlsOperationStatus, diagnostic SYSLIB5007.
  • HTTP request compression: GZipCompressedContent, BrotliCompressedContent, ZstandardCompressedContent.
  • SocketsHttpHandler: ShouldEvictConnection retires connections by age, endpoint and DNS changes; InitialHttp2MaxConcurrentStreams limits the initial burst before the SETTINGS frame (minimum value 1).
  • DNS: Dns.ResolveSrv, ResolveMx, ResolveTxt, ResolveCName, ResolvePtr, ResolveNs (and Async variants) with DnsResult<T>; the DnsResolver class with DnsResolverOptions accepts custom DNS servers and now works on Linux too.
  • HTTP/2: HttpClient automatically downgrades to HTTP/1.1 when Windows authentication (NTLM/Negotiate) is required.
  • QUIC: QuicStream.Priority (0 to 255, default 127) and DefaultPriority.
  • Also: MediaTypeNames.Video constants; the HTTP open_connections and active_requests metrics become observable instruments (call MeterListener.RecordObservableInstruments()).

Cryptography

  • X25519: the X25519DiffieHellman class with GenerateKey() and DeriveRawSecretAgreement, plus PKCS#8, SPKI and PEM import/export.
  • FixedTimeEquals: a new overload compares a span against a single byte in constant time.
  • AES Key Wrap: RFC 3394 (EncryptKeyWrap, DecryptKeyWrap, multiples of 8 bytes) and RFC 5649 (EncryptKeyWrapPadded, any length), with array and span overloads.
  • Apple platforms: AesGcm and ChaCha20Poly1305 avoid passing empty associated data to CryptoKit.
  • ML-KEM and HPKE (experimental): CompositeMLKem (SYSLIB5006) combines post-quantum and classical KEMs; Hpke (SYSLIB5009) uses HpkeSuite with Seal and Open. Suite availability depends on the platform.
  • CMS: EnvelopedCms encrypts with pure ML-KEM recipients, on non-Windows platforms only.

Configuration, options and validation

  • Binding: ConfigurationIgnoreAttribute opts properties out of binding; empty arrays bind to constructor parameters; PhysicalFilesWatcher is more reliable with missing directories and file systems without watching.
  • OptionsBuilder: Validate<TValidator>() with an IValidateOptions<TOptions> registered in DI.
  • ChangeToken.OnChange: Func<Task> overloads, no async void.
  • HybridCache: GetOrCreateAsync overloads with a mutable context for expiration and local cache size.
  • Async DataAnnotations: AsyncValidationAttribute, IAsyncValidatableObject, Validator.ValidateObjectAsync and friends; async options validation with IAsyncValidateOptions and IAsyncStartupValidator (IStartupValidator is obsolete); ValidationAttribute.FormatMessage for localization.

Diagnostics and logging

  • MemoryCache and OpenTelemetry: with TrackStatistics = true, the Microsoft.Extensions.Caching.Memory.MemoryCache meter publishes dotnet.cache.requests (tag dotnet.cache.request.result), dotnet.cache.evictions, dotnet.cache.entries and dotnet.cache.estimated_size; an IMeterFactory gives per-instance metrics.
  • Rule-based tracing: AddTracing with EnableTracing/DisableTracing for sources and operations, drivable from configuration; ActivitySourceFactory and an unsealed ActivitySource.
  • Generic logging: generic LoggerMessage methods avoid boxing (the allows ref struct anti-constraint is unsupported: SYSLIB1011).

LINQ

LeftJoin, RightJoin and the new FullJoin return tuples; Join and GroupJoin gain tuple-returning overloads with no result selector and an optional IEqualityComparer<T>. They are available on Enumerable, Queryable and AsyncEnumerable.

Sources

Comments (0)

No comments yet.

Leave a comment