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

C# REST请求修正拼写错误后进入catch块 无法正确获取place_id

问题解决方案

核心错误原因

从你给出的接口返回JSON可以看出,candidates 是数组类型,数组的元素才是包含place_id字段的对象,你原有代码直接将candidates当作普通对象访问place_id,完全不匹配数据结构,所以会抛出异常。

修正后的代码

public async Task<string> GetPlaceAsync(string cityname, string countrycode)
{
    string thereturn = "";
    // 注意:HttpClient不建议每次请求都new,建议全局单例复用,避免端口耗尽问题
    var client = new HttpClient();
    // 对输入参数做URL编码,避免特殊字符导致请求异常
    var encodedInput = Uri.EscapeDataString($"{cityname},{countrycode}");
    var uri = new Uri($"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input={encodedInput}&inputtype=textquery&key={apikey}");
    try
    { 
        var response = await client.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            var jsonData = (JObject)JsonConvert.DeserializeObject(result);
            var status = jsonData["status"].Value<string>();

            if (status != "ZERO_RESULTS" && jsonData["candidates"]?.HasValues == true)
            {
                // 先取数组的第一个元素,再取元素下的place_id
                var message = jsonData["candidates"][0]["place_id"].Value<string>();
                System.Diagnostics.Debug.WriteLine(message);
                return message;
            }
            else
                thereturn = status;
        }
        else 
            thereturn = "fail";
    }
    catch (Exception ex) 
    {
        // 实际开发中可在此记录异常详情,方便后续排查问题
        thereturn = "Connection-error"; 
    }
    return thereturn;
}

额外优化建议

  • HttpClient 建议全局单例复用,不要每次请求都实例化,高并发场景下频繁实例化会出现端口耗尽的问题
  • 增加candidates非空、有元素的判断,避免极端场景下的空引用异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:45:03