Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

c# - How to add bearer token to autogenerated OpenApiToCSharpClient?

I have client generated using OpenApiToCSharpClient but each request is 401 unauthorized. I have added bearer token in HttpClient like this:

ClientEngine.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Token);

and generated client is used like this:

 var userClient = new UserClient(HttpClient);
 UserAll.AddRange(await userClient.GetAllAsync());

but problem is that auth header isn't added to request (autogenerated code follows):

...
request_.Method = new System.Net.Http.HttpMethod("GET");
                request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

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

Request is sent but only the client_ object has authorization headers but request_ does not. As far as I know, authorization headers should be also added to request but they aren't. I don't have any property related to authorization in nswag.json file - only following properties are related to HttpClient:

  "disposeHttpClient": true,
  "injectHttpClient": true,
  "httpClientType": "System.Net.Http.HttpClient",

What is missing?

question from:https://stackoverflow.com/questions/65858646/how-to-add-bearer-token-to-autogenerated-openapitocsharpclient

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Everything above is correct but apparently, automatic redirection to https was issue - somehow, when request is upgraded from http to https (automatically), it strips the headers. Interestingly enough, Postman didn't have this problem, only HttpClient.

Solution - in Startup.cs, do this:

 if (!env.IsDevelopment())
 {
     app.UseHttpsRedirection();
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...