c# - 如何在 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
解决方案
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
.
推荐阅读
- python - Python 3 写入 json 文件时出现双反斜杠问题
- python - 一种具有可变长度输入的热编码
- azure - 启用 Windows 安全事件的 Azure 安全中心 ARM 模板
- scala - 使用 Option[List[Long]] 时用 None 替换空列表
- linux - 找到所有具有特定扩展名的文件然后执行
- node.js - 在 Postgres 查询中调用本地函数
- python - 在填写用户名和密码时,元素在 selenium python 中不是难以处理的
- android - 提交失败,错误 0 文件已提交。不会添加文件别名 XXX 已存在于索引中
- matlab - 符号矩阵在 Matlab 中没有完全简化,但在 Octave 中简化了
- dji-sdk - DJIRTKState:distanceToHomePointDataSource 是 DJIRTKDataSource 类型而不是距离类型