You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用OpenRouteService API遇Authorization缺失错误求解决

解决OpenRouteService API调用的"Authorization field missing"错误

问题根源

你的代码存在两个关键问题:

  • 请求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返回的嵌套结构定义属性
}

关键修改说明

  1. 正确设置BaseAddress:将BaseAddress设为API根地址,后续请求只需拼接相对路径与参数,避免URL拼接错误。
  2. 使用Authorization请求头:用Bearer {api_key}格式在请求头传递密钥,这是官方推荐的认证方式,既安全又能解决授权字段缺失问题。
  3. 修复请求URL:直接构造正确的相对路径参数,消除无效的路径拼接。
  4. 添加请求校验:调用response.EnsureSuccessStatusCode(),在请求失败时抛出异常,快速定位问题。

额外提示

  • 必须保证RouteInfo类的属性与OpenRouteService返回的GeoJSON结构完全匹配,可借助在线JSON转C#工具生成对应实体类,否则反序列化会失败。
  • 建议复用HttpClient实例,不要每次请求都新建,这是HttpClient的最佳实践,避免耗尽套接字资源。

内容的提问来源于stack exchange,提问作者iMissTheName

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:50:21