C#调用OpenRouteService API遇Authorization缺失错误求解决
问题根源
你的代码存在两个关键问题:
- 请求URL构造错误:把带参数的完整端点设为
BaseAddress后,又在GetAsync中追加了"directions",导致实际请求的URL变成https://api.openrouteservice.org/v2/directions/driving-car?api_key=.../directions,完全偏离了正确的API端点。 - API密钥传递方式不规范:虽然OpenRouteService支持URL参数传
api_key,但部分场景下API会优先校验请求头中的Authorization字段,这也可能触发"Authorization field missing"错误。
修正后的代码
using Newtonsoft.Json; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; class OpenRouteServiceCall { private readonly string _apiKey = "my_key_number"; private readonly HttpClient _client; public OpenRouteServiceCall() { _client = new HttpClient { BaseAddress = new Uri("https://api.openrouteservice.org/") }; // 设置接受的响应格式 _client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/geo+json")); // 添加Authorization请求头(官方推荐方式) _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey); } public async Task<RouteInfo> GetRouteInfo() { // 构造正确的请求路径与参数 var requestUrl = "v2/directions/driving-car?" + "start=27.589244,47.160306" + "&end=27.72833,46.641804"; using (var response = await _client.GetAsync(requestUrl)) { // 校验请求是否成功,失败时直接抛出异常便于调试 response.EnsureSuccessStatusCode(); string responseData = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseData); return JsonConvert.DeserializeObject<RouteInfo>(responseData); } } } // 需根据OpenRouteService返回的GeoJSON结构调整的实体类示例 public class RouteInfo { // 匹配API返回的核心字段,需根据实际返回数据补充完整 public double Distance { get; set; } public double Duration { get; set; } // 若需speed、congestion等字段,需对应API返回的嵌套结构定义属性 }
关键修改说明
- 正确设置BaseAddress:将
BaseAddress设为API根地址,后续请求只需拼接相对路径与参数,避免URL拼接错误。 - 使用Authorization请求头:用
Bearer {api_key}格式在请求头传递密钥,这是官方推荐的认证方式,既安全又能解决授权字段缺失问题。 - 修复请求URL:直接构造正确的相对路径参数,消除无效的路径拼接。
- 添加请求校验:调用
response.EnsureSuccessStatusCode(),在请求失败时抛出异常,快速定位问题。
额外提示
- 必须保证
RouteInfo类的属性与OpenRouteService返回的GeoJSON结构完全匹配,可借助在线JSON转C#工具生成对应实体类,否则反序列化会失败。 - 建议复用
HttpClient实例,不要每次请求都新建,这是HttpClient的最佳实践,避免耗尽套接字资源。
内容的提问来源于stack exchange,提问作者iMissTheName
相关产品推荐
相关产品推荐

