Autorest:在查询字符串中进行身份验证

Autorest: Authenticating in Query String

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

更具体地说,swagger 安全定义是

"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 作为参数。与 headers 不同,我不能只创建一个在 HttpClient 上设置默认值 header 的构造函数。

如何生成允许我设置 api 键的代码客户端?

附加说明:我也接受其他生成器,如 NSwag。不幸的是,截至 2019-06 年,NSwag does not handle security definitions in generation

您需要实施 ServiceClientCredentials class 并覆盖 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);
        }
    }