Path: redb-route/redb.Route/Serialization/FormBody.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Serialization/FormBody.cs
----
using System.Collections;
namespace redb.Route.Serialization;
///
/// The fields of an application/x-www-form-urlencoded body, in order. A name may repeat (checkboxes, a list
/// field), so the form is a list of pairs; answers the first value of a name and
/// every one. Names compare ordinally, as HTML forms send them.
///
public sealed class FormBody : IReadOnlyList>, ICloneable
{
private readonly List> _fields;
/// An empty form.
public FormBody() => _fields = [];
/// A form with the given fields, in order.
public FormBody(IEnumerable> fields)
{
ArgumentNullException.ThrowIfNull(fields);
_fields = [];
foreach (var (name, value) in fields)
Add(name, value);
}
///
public int Count => _fields.Count;
///
public KeyValuePair this[int index] => _fields[index];
/// Appends a field; a field with the same name may already be there.
public FormBody Add(string name, string value)
{
ArgumentNullException.ThrowIfNull(name);
ArgumentNullException.ThrowIfNull(value);
_fields.Add(new(name, value));
return this;
}
/// The first value of , or null.
public string? Get(string name)
{
ArgumentNullException.ThrowIfNull(name);
foreach (var (key, value) in _fields)
if (string.Equals(key, name, StringComparison.Ordinal))
return value;
return null;
}
/// Every value of , in order; empty when the field is absent.
public IReadOnlyList GetAll(string name)
{
ArgumentNullException.ThrowIfNull(name);
return _fields.Where(f => string.Equals(f.Key, name, StringComparison.Ordinal)).Select(f => f.Value).ToArray();
}
/// Whether the form has a field named .
public bool Contains(string name) => Get(name) is not null;
/// The fields as a dictionary of the first value of each name (later repeats are left out).
public Dictionary ToDictionary()
{
var map = new Dictionary(StringComparer.Ordinal);
foreach (var (key, value) in _fields)
map.TryAdd(key, value);
return map;
}
/// A copy with its own field list (names and values are immutable strings).
public object Clone() => new FormBody(_fields);
///
public IEnumerator> GetEnumerator() => _fields.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// The form in its wire form, UTF-8 (for logs and tests).
public override string ToString() => FormUrlEncoding.Encode(this, System.Text.Encoding.UTF8);
}