What is the purpose of HttpHeaders.TryAddWithoutValidation?

.net, c#

Solution

Using Reflector, this is what the TryAddWithoutValidation method does internally:

if (!this.TryCheckHeaderName(name))
{
    return false;
}
if (value == null)
{
    value = string.Empty;
}
AddValue(this.GetOrCreateHeaderInfo(name, false), value, StoreLocation.Raw);
return true;

The work happens inside the `TryCheckHeaderName()` function.

It boils down to checking whether the name is not null and whether it matches the RFC for the HTTP protocol (i.e. it contains no invalid characters etc.) as well as checking the header against a set of not-allowed headers.

Here's the source-code:

bool TryCheckHeaderName(string name)
{
   if (string.IsNullOrEmpty(name))
   {
       return false;
   }
   if (HttpRuleParser.GetTokenLength(name, 0) != name.Length)
   {
       return false;
   }
   if ((this.invalidHeaders != null) && this.invalidHeaders.Contains(name))
   {
       return false;
   }
   return true;
}

In contrast the Add method has similar behavior with the exception(pun intended) that it throws an exception in case the header name fails any one of the conditions in the `TryCheckHeaderName` function.

Problem

In the System.Net.Http.Headers namespace, what is the difference between HttpHeaders.TryAddWithoutValidation and HttpHeaders.Add? Specifically, what validation is occurring when calling the Add method? The documentation for Add() simply states: "The header value will be parsed and validated."

Original source