GenericHeaderParser
Represents a generic header parser.
public abstract class GenericHeaderParser<T> : object
Remarks
This is an abstract class that provides a base implementation for parsing HTTP headers that have a simple, comma-separated list of values. Derived classes can inherit from this class to implement parsing logic for specific header types.
The primary purpose of this class is to enable the deserialization of string representations of header values into strongly-typed objects. It handles common parsing scenarios like splitting by commas, trimming whitespace, and handling quoted strings.
Methods
Parse
Abstract method that must be implemented by derived classes to perform the actual parsing of a single header value.
protected abstract T Parse(string value);
GetHeaderValueFromString
Helper method to split a header string into individual values, handling quoted strings correctly.
protected static ICollection<string> GetHeaderValueFromString(string value);
This method is useful for preprocessing the header string before passing individual values to the Parse method.
Usage Example
Here's a simplified example of how you might create a derived parser for a hypothetical 'X-My-Custom-Header':
using System.Collections.Generic;
using System.Net.Http.Headers;
public class MyCustomHeaderValue
{
public string Name { get; set; }
public int Id { get; set; }
public override string ToString()
{
return $"{Name}:{Id}";
}
}
public class MyCustomHeaderParser : GenericHeaderParser<MyCustomHeaderValue>
{
public MyCustomHeaderParser() : base(false) { } // The second parameter indicates if whitespace is allowed around commas
protected override MyCustomHeaderValue Parse(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
var parts = value.Split(':');
if (parts.Length == 2 && int.TryParse(parts[1], out int id))
{
return new MyCustomHeaderValue { Name = parts[0], Id = id };
}
// Handle invalid format if necessary, or throw an exception
return null;
}
}
// --- Usage ---
/*
var parser = new MyCustomHeaderParser();
string headerString = "Item1:100, Item2:200"; // Or "Item1: 100, Item2: 200" if whitespace is allowed
ICollection<string> values = GetHeaderValueFromString(headerString); // This method is protected, so you might need to access it via a derived instance or a static helper.
List<MyCustomHeaderValue> parsedValues = new List<MyCustomHeaderValue>();
foreach (var val in values)
{
var parsed = parser.Parse(val); // Calling the protected Parse method directly for demonstration
if (parsed != null)
{
parsedValues.Add(parsed);
}
}
// parsedValues will contain MyCustomHeaderValue objects for "Item1:100" and "Item2:200"
*/