首页 > 解决方案 > 如何在 c# 中将查询字符串添加到 HttpClient.BaseAdress 中?

问题描述

我正在尝试将查询字符串传递给 BaseAddress,但它无法识别引号“?”。

引用打破了URI

首先我创建我的 BaseAddress

httpClient.BaseAddress = new Uri($"https://api.openweathermap.org/data/2.5/weather?appid={Key}/"); 

然后我调用 GetAsync 方法,尝试添加另一个参数

using (var response = await ApiHelper.httpClient.GetAsync("&q=mexico"))....

这是代码调用的 URI

https://api.openweathermap.org/data/2.5/&q=mexico

标签: c#httpclient

解决方案


DelegatingHandler如果您需要将 API 密钥应用于每个请求,我会很想使用:

private class KeyHandler : DelegatingHandler
{
    private readonly string _escapedKey;

    public KeyHandler(string key)  : this(new HttpClientHandler(), key)
    {
    }

    public KeyHandler(HttpMessageHandler innerHandler, string key) : base(innerHandler)
    {
        // escape the key since it might contain invalid characters
        _escapedKey = Uri.EscapeDataString(key);
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // we'll use the UriBuilder to parse and modify the url
        var uriBuilder = new UriBuilder(request.RequestUri);

        // when the query string is empty, we simply want to set the appid query parameter
        if (string.IsNullOrEmpty(uriBuilder.Query))
        {
            uriBuilder.Query = $"appid={_escapedKey}";
        }
        // otherwise we want to append it
        else
        {
            uriBuilder.Query = $"{uriBuilder.Query}&appid={_escapedKey}";
        }
        // replace the uri in the request object
        request.RequestUri = uriBuilder.Uri;
        // make the request as normal
        return base.SendAsync(request, cancellationToken);
    }
}

用法:

httpClient = new HttpClient(new KeyHandler(Key));
httpClient.BaseAddress = new Uri($"https://api.openweathermap.org/data/2.5/weather"); 

// since the logic of adding/appending the appid is done based on what's in
// the query string, you can simply write `?q=mexico` here, instead of `&q=mexico`
using (var response = await ApiHelper.httpClient.GetAsync("?q=mexico"))

** 注意:如果你使用的是 ASP.NET Core,你应该调用services.AddHttpClient()然后使用IHttpHandlerFactory来生成KeyHandler.


推荐阅读