I use NSwagStadio to write httpClient codes.I use authorization in api. I can login and register with httpClient codes but when I want to access apiControllers that need authentication I get 401 status code.All codes work correct if I remove authorization from apiController. I think I found where is the problem but I dont know how to fix it.
here is the problem in codes that NSwag made:
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/LeaveTypes");
var client_ = _httpClient;
var disposeClient_ = false;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain"));
PrepareRequest(client_, request_, urlBuilder_);
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
PrepareRequest(client_, request_, url_);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var disposeResponse_ = true;
in pictures below you can see client_ have authentication header but request_ authentication header is null so response_ get 401 error.
here is the picture that shows client have authorization header:
and here is the picture that shows request doesnt have authorization header:
I added manually this code but still doesnt work
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
PrepareRequest(client_, request_, url_);
//I add this line
request_.Headers.Authorization = new AuthenticationHeaderValue(client_.DefaultRequestHeaders.Authorization.Scheme, client_.DefaultRequestHeaders.Authorization.Parameter);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var disposeResponse_ = true;
the token is correct.I used the token in api project and it works but httpClient doesnt send the token