BaltoStar
BaltoStar

Reputation: 8997

.NET HttpRequestMessage : possible to add header with blank value?

Is it possible to add a header with value = blank/missing ?

HttpRequestMessage.Headers.Add("header-name", string.Empty);

System.FormatException was unhandled by user code
  HResult=-2146233033
  Message=The format of value '' is invalid.
  Source=System.Net.Http
  StackTrace:
       at System.Net.Http.Headers.HttpHeaderParser.ParseValue(String value, Object storeValue, Int32& index)
       at System.Net.Http.Headers.HttpHeaders.ParseAndAddValue(String name, HeaderStoreItemInfo info, String value)
       at System.Net.Http.Headers.HttpHeaders.Add(String name, String value)
       at 

Upvotes: 1

Views: 3953

Answers (3)

kiewic
kiewic

Reputation: 16450

If you want to send a crazy header without value, use TryAddWithoutValidation() method, here an example:

HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri("http://kiewic.com");
var result = request.Headers.TryAddWithoutValidation("Authorization", string.Empty);

HttpClient client = new HttpClient();
var response = await client.SendAsync(request);

And cross fingers so the server likes the request.

Upvotes: 3

Kapil
Kapil

Reputation: 1931

You can get an empty instance of HttpHeaders in one of the following ways:

var headers = new HttpClient().DefaultRequestHeaders;
var headers = new HttpResponseMessage().Headers;
var headers = new HttpRequestMessage().Headers;
You could also make your own class that extends HttpHeaders and use that.

Upvotes: 0

Adam Zuckerman
Adam Zuckerman

Reputation: 1641

That would be no. It goes against the HTTP protocol standard.

4.2 Message Headers

HTTP header fields, which include general-header (section 4.5), request-header (section 5.3), response-header (section 6.2), and entity-header (section 7.1) fields, follow the same generic format as that given in Section 3.1 of RFC 822 [9]. Each header field consists of a name followed by a colon (":") and the field value.

Upvotes: 1

Related Questions