Skip to content

Instantly share code, notes, and snippets.

@mishrsud
Created February 14, 2016 11:10
Show Gist options
  • Save mishrsud/78de0300a129d32240b0 to your computer and use it in GitHub Desktop.
Save mishrsud/78de0300a129d32240b0 to your computer and use it in GitHub Desktop.
/// <summary>
/// Gets the first header value or default.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="requestMessage">The <see cref="HttpRequestMessage"/> message.</param>
/// <param name="headerKey">The header key i.e. the header to read.</param>
/// <param name="defaultValueSelector">The <see cref="Func{T, TResult}"/> default value selector.</param>
/// <param name="valueTransform">The <see cref="Func{T, TResult}"/> value transform.</param>
/// <returns></returns>
private T GetFirstHeaderValueOrDefault<T>(
HttpRequestMessage requestMessage,
string headerKey,
Func<HttpRequestMessage, string> defaultValueSelector,
Func<string, T> valueTransform)
{
IEnumerable<string> headerValues;
HttpRequestMessage httpRequestMessage = requestMessage ?? new HttpRequestMessage();
// If the header is not found, run the default value selector, transform to T and return
if (!httpRequestMessage.Headers.TryGetValues(headerKey, out headerValues))
{
return valueTransform(defaultValueSelector(httpRequestMessage));
}
// header found, check if its value is null
string headerValue = headerValues.FirstOrDefault() ?? defaultValueSelector(httpRequestMessage);
return valueTransform(headerValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment