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

Blazor中调用Bing WebAPI及高程接口出现字符串格式化异常求助

解决Blazor中构造Open-Meteo高程请求Uri时的格式错误

错误根源

你遇到的Incorrect String Format Exception是因为使用string.Format时用了命名占位符({latitude}、{longitude}),但string.Format仅支持索引占位符({0}、{1})或者配合C# 6+的字符串插值语法。这行代码在任何.NET项目中都会报错,可能你之前的普通Web项目里实际用了正确写法却没注意到。

修复方案

以下两种方法都能解决问题,推荐使用字符串插值(更简洁直观):

方法1:使用字符串插值(推荐)

直接用$前缀包裹字符串,将变量嵌入其中:

Uri elevationReq = new Uri($"https://api.open-meteo.com/v1/elevation?latitude={latitude}&longitude={longitude}");

方法2:使用string.Format的索引占位符

如果坚持使用string.Format,需要将变量作为参数传递,并用索引占位符对应:

Uri elevationReq = new Uri(string.Format("https://api.open-meteo.com/v1/elevation?latitude={0}&longitude={1}", latitude, longitude));

额外优化建议

  1. 正确使用HttpClient
    Blazor中不要在方法内手动创建HttpClient(new HttpClient()),频繁创建会耗尽套接字资源。应该通过依赖注入获取:
@inject HttpClient HttpClient

然后在Submit方法中直接使用注入的HttpClient,移除using (HttpClient client = new HttpClient())代码块。

  1. 优化错误处理
    当前catch块只显示模糊的"Invalid Location",建议输出具体错误信息方便调试:
catch (Exception e)
{
    loc = "";
    errmsg = $"请求失败:{e.Message}";
    Console.WriteLine($"详细错误:{e.ToString()}");
}
  1. 不要硬编码密钥
    Bing Maps密钥硬编码在代码里不安全,建议放在appsettings.json中,通过IConfiguration读取:
// appsettings.json
{
  "BingMapsApiKey": "你的密钥"
}

然后在组件中注入IConfiguration读取:

@inject IConfiguration Config
string key = Config["BingMapsApiKey"];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:36:11