调用Bing Image Search API返回无关结果,请求排查问题
问题描述
调用Bing Image Search API的脚本在搜索a puppy时能正确返回小狗图片,但搜索mo farah时得到大量无关图片。脚本基于微软官方REST示例实现,异常结果如图:

代码如下:
public async Task CallBing(string queryTerm, int count, string aspect = "All", string size = "Large", string color = "ColorOnly", string license = "Public") { queryTerm = queryTerm.Replace(" ", "+"); // Replace with your Bing Image API key var apiUrl = $"https://api.bing.microsoft.com/v7.0/images/search?q={queryTerm}" //imageType + $"&count={count}" // Limit the number of results to 10 + $"&imageType=Photo" + $"&mkt=en-us" + $"&aspect={aspect}" // Limit the results to square images + $"&size={size}" // Limit the results to medium-sized images + $"&color={color}" // Limit the results to color images only + $"&license={license}"; // Limit the results to images with public licenses try { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"); client.DefaultRequestHeaders.Add("X-MSEdge-ClientIP", "999.999.999.999"); client.DefaultRequestHeaders.Add("X-Search-Location", "lat:47.60357;long:-122.3295;re:100"); var response = await client.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize<BingImageResult>(content); int i = 0; foreach (var image in result.value) { Console.WriteLine(image.contentUrl); using (WebClient dlclient = new WebClient()) { try { dlclient.DownloadFile(new Uri(image.contentUrl), @$"c:\temp\bings\{i}.jpg"); } catch (Exception dlEx) { Console.WriteLine($"Error Downloading image {dlEx.Message}"); } } i++; } } else { Console.WriteLine($"Failed to retrieve images: {response.ReasonPhrase}"); } } } catch (Exception ex) { Console.WriteLine(ex.Message); // throw; } Console.ReadKey(); }
问题排查与修复方案
1. 替换错误的Query编码方式
手动用Replace(" ", "+")处理空格不符合标准URL编码规范,虽然对简单关键词有效,但可能导致API对特定名称(如mo farah)的解析出现偏差。应使用官方的URL编码方法:
// 替换原有query处理行 queryTerm = Uri.EscapeDataString(queryTerm);
2. 移除干扰结果的硬编码地理位置参数
你在请求头中硬编码了西雅图地区的X-Search-Location和虚假的X-MSEdge-ClientIP,Bing搜索结果会根据地理位置做本地化调整,对于英国运动员Mo Farah来说,该地理位置会降低相关结果的优先级,导致返回无关内容。
- 直接移除这两个请求头:
// 注释或删除以下两行 // client.DefaultRequestHeaders.Add("X-MSEdge-ClientIP", "999.999.999.999"); // client.DefaultRequestHeaders.Add("X-Search-Location", "lat:47.60357;long:-122.3295;re:100");
- 若需要指定地理位置,建议使用与目标内容匹配的真实坐标(如英国伦敦)。
3. 调整过严的过滤参数
当前设置的color=ColorOnly、license=Public、size=Large等过滤条件,可能导致Mo Farah的符合条件的图片数量不足,API返回低相关度结果填充数量。可以先暂时移除部分过滤参数测试,确认有效后再逐步添加。
4. 修正参数与注释不一致问题
代码中存在参数与注释矛盾的情况,虽然不直接导致无关结果,但会增加排查难度:
aspect参数注释标注为"限制方形图片",但默认传值是All,若需要方形图应改为Squaresize参数注释标注为"中等尺寸图片",但默认传值是Large,需修正注释或参数值
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

