简体   繁体   English

如何将不记名令牌添加到自动生成的 OpenApiToCSharpClient?

[英]How to add bearer token to autogenerated OpenApiToCSharpClient?

I have client generated using OpenApiToCSharpClient but each request is 401 unauthorized.我有使用 OpenApiToCSharpClient 生成的客户端,但每个请求都是 401 未经授权的。 I have added bearer token in HttpClient like this:我在 HttpClient 中添加了不记名令牌,如下所示:

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):但问题是 auth header 未添加到请求中(自动生成的代码如下):

...
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.请求已发送,但只有client_具有授权标头,但request_没有。 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:我在nswag.json文件中没有任何与授权相关的属性 - 只有以下属性与 HttpClient 相关:

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

What is missing?什么不见了?

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.上面的一切都是正确的,但显然,自动重定向到 https 是问题 - 不知何故,当请求从 http 升级到 https(自动)时,它会剥离标题。 Interestingly enough, Postman didn't have this problem, only HttpClient .有趣的是, Postman 没有这个问题,只有HttpClient

Solution - in Startup.cs , do this:解决方案 - 在Startup.cs中,执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM