1

我正在使用需要通过查询字符串进行身份验证的 REST Api。

更具体地说,招摇的安全定义是

"securityDefinitions": {
  "api_token": {
    "type": "apiKey",
    "name": "api_token",
    "description": "<p>Authentication is handled via API tokens that you need to send as a GET parameter when making any request to our API.</p>\n            <p>To request an API token you need to your settings page on our website and press \"Send Token to Email\" button.</p>",
    "in": "query"
  }
},
"security": [{"api_token": []}],

但是,各个操作不包含api_key作为参数。与标头不同,我不能只创建一个在 HttpClient 上设置默认标头的构造函数。

如何生成让我设置 api 密钥的代码客户端?

附加说明:我也接受其他生成器,如 NSwag。不幸的是,截至 2019-06,NSwag不处理生成中的安全定义

4

1 回答 1

1

您需要实现 ServiceClientCredentials 类并覆盖 ProcessHttpRequestASync 方法。然后自己手动添加查询字符串

public class MyCreds : ServiceClientCredentials
    {
        public override void InitializeServiceClient<T>(ServiceClient<T> client)
        {
            base.InitializeServiceClient(client);
        }
        public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {  request.RequestUri = new System.Uri(request.RequestUri.OriginalString + "?api_key=abc");
            return base.ProcessHttpRequestAsync(request, cancellationToken);
        }
    }
于 2019-11-11T23:10:33.903 回答