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."
public final class HttpHeaders extends Object. A read-only view of a set of HTTP headers. An HttpHeaders is not typically created directly, but rather returned from an HttpRequest or an HttpResponse . Specific HTTP headers can be set for a request through one of the request builder's headers methods.
There are two ways by which we can add the headers. One, we add the HTTP Headers while making a request. The second way is to use the HTTP interceptor to intercept all the Requests and add the Headers. In both cases, we use the httpHeaders configuration option provided by angular HttpClient to add the headers.
TryAddWithoutValidation
does not try to parse the value it is given to see if it is valid (e.g. valid "type" of value or multiple values for a single-value header). Add
first parses the value to perform the previously mentioned checks before trying the add the header value
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With