The default request header does not accept a value that is always zero.

I am doing a web api integration test.

I want to pass the carrier token to the Http request header:

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eJ43k5l435j34l5j43l5j34l5jl35j34l5j344l.4534535.534534sample..."); 

When this line of code is executed, I look at the httpClient.DefaultRequestHeaders.Authorization property and is it NULL?

Why is this?

UPDATE

This is from the base class of my integration test class:

  protected HttpClient Client { get { return server.HttpClient; } } 

When I manually update the http client in the test class:

 var client = new HttpClient(); client.DefaultRequestHeaders.Add("key","value"); 

It works, but not with my client !?

UPDATE 2

OK I found this:

  var c = Client; c.DefaultRequestHeaders.Add("bla", "bla"); 

IT WORKS, but why should I read my client in a new variable?

+7
asp.net-web-api asp.net-web-api2
source share
1 answer

I read (in an article I cannot find, sorry) that the Auth headers on the HttpClient (especially on the testServer inmemory node, which apparently cannot handle authenticated services and therefore seems useless to me? See https: // blog.kloud.com.au/2014/10/26/asp-net-web-api-integration-testing-with-one-line-of-code/ "Unfortunately, the solution for working with memory does not work for me from boxes. It doesn't seem like descriptor authentication. I use UseJwtBearerAuthentication (JWT token-broker-broker) and my api calls are 401 ") in webapi - only GET - I had the same problem, I tried to execute integration tests with authenticated endpoints - I received a bearer token, added it to the header, but in the next line of code, it was NULL.

The advice I found (and the solution I got) was to add the Bearer header to the HttpRequestMessage headers, not the HttpClient headers, and then use HttpClient.SendAsync, not HttpClient.PostAsync (which apparently for any reason, messages, not headers).

I have already spent a lot of time trying to figure this out, and most of the tutorials you find do NOT handle auth headers, so I am surprised that more people do not discuss this issue (assuming, of course, that I am not just a muppet). But yes, try adding your auth headers to the request message, not to the http client.

0
source share

All Articles