6

我正在使用 Refit 为 Web 服务生成客户端。

我的 Web API 的所有 URL 都是这样的:

https://service.com/api/v3/datasetsapi_key=XXXXXXX

如您所见,API 密钥是在查询字符串而不是标头中指定的。

我希望 Refit 自动提供我的访问令牌作为查询字符串的一部分,而不必在我的服务接口中指定它。

我查看了文档,但我还没有找到方法。

4

1 回答 1

8

最后,我创建了一个HttpMessageHandler拦截请求并在查询字符串中注入“api_key”的代码,代码如下:

服务创建

service = RestService.For<IMyService>(new HttpClient(new QuerystringInjectingHttpMessageHandler(("api_key", token)))
    {
        BaseAddress = uri,
    });

处理程序

public class QuerystringInjectingHttpMessageHandler : DelegatingHandler
{
    private readonly (string Key, string Value)[] injectedParameters;

    public QuerystringInjectingHttpMessageHandler(params (string key, string value)[] injectedParameters) : this()
    {
        this.injectedParameters = injectedParameters;
    }

    public QuerystringInjectingHttpMessageHandler() : base(new HttpClientHandler())
    {
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var finalUri = InjectIntoQuerystring(request.RequestUri, injectedParameters);

        request.RequestUri = finalUri;

        return base.SendAsync(request, cancellationToken);
    }

    private static Uri InjectIntoQuerystring(Uri uri, IEnumerable<(string Key, string Value)> parameters)
    {
        var uriStr = uri.ToString();

        var queryString = new string(uriStr.SkipWhile(c => c != '?').ToArray());
        var baseUri = uriStr.Substring(0, uriStr.Length - queryString.Length);
        var currentParameters = HttpUtility.ParseQueryString(queryString);

        foreach (var (key, value) in parameters)
        {
            currentParameters[key] = value;
        }

        var tuples = currentParameters.ToTuples();

        var newUri =
            string.Join("&", tuples.Select(tuple =>
            {
                if (tuple.name == null)
                {
                    return tuple.value;
                }

                return tuple.name + "=" + tuple.value;
            }));

        var suffix = newUri == "" ? "" : "?" + newUri;
        var finalUri = new Uri(baseUri + suffix);
        return finalUri;
    }
}

延期

public static class Extensions
{
    public static IEnumerable<(string name, string value)> ToTuples(this NameValueCollection collection)
    {
        if (collection == null)
        {
            throw new ArgumentNullException("collection");
        }

        return
            from key in collection.Cast<string>()
            from value in collection.GetValues(key)
            select (key, value);
    }
}
于 2020-02-12T10:38:51.747 回答