Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of HttpHeaders.TryAddWithoutValidation?

Tags:

c#

.net

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."

like image 242
kaliatech Avatar asked Feb 20 '13 21:02

kaliatech


People also ask

What is HttpHeaders in Java?

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.

How do I set HttpHeaders?

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.


2 Answers

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

like image 183
Peter Ritchie Avatar answered Nov 06 '22 21:11

Peter Ritchie


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.

like image 31
Mike Dinescu Avatar answered Nov 06 '22 22:11

Mike Dinescu