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

.NET Core控制台应用调用Graph API SharePoint Search遇区域必填错误求助

问题:使用应用权限调用Microsoft Graph Search API报错,需服务身份解决方案

现有实现代码

1. Azure AD应用身份认证代码

通过clientId和clientSecret获取Graph API访问令牌:

string tenantName = "MY.TENANT";
string authUrl = "https://login.microsoftonline.com/" + tenantName;
var clientId = "MYID";
var clientSecret = "MYSECRET";
AuthenticationContext authenticationContext = new AuthenticationContext(authUrl, false);

ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult;

authenticationResult = await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com/", clientCred);
return authenticationResult.AccessToken;

2. 成功调用SharePoint列表的代码

获取令牌后,可正常调用SharePoint列表接口获取数据:

using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, $"{graphUrl}/sites/{siteId}/lists/MYLISTGUID/items?expand=fields");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
    var responseString = response.Content.ReadAsStringAsync().Result;
    return responseString;
}

3. Search API调用问题

调用Graph Search API时出现错误:SearchRequest Invalid (Region is required when request with application permission.),调用代码如下:

using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"{graphUrl}/search/query/");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var filter = new
{
    Requests = new[] { 
        new {
            EntityTypes = new[] { "listItem" },
            Query = new
            {
                QueryString = "Pio*"
            }
        }
    }
};

request.Content = new StringContent(JsonConvert.SerializeObject(filter), Encoding.UTF8, "application/json");

var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
    var responseString = response.Content.ReadAsStringAsync().Result;
}

相同查询在Graph Explorer中可正常执行,但场景需要以服务用户身份(应用权限)调用,用于迁移SharePoint本地解决方案。

解决思路

  1. 添加Region参数解决报错
    错误提示明确说明应用权限调用时必须指定Region,需修改搜索请求的JSON体,在每个搜索请求对象中添加Region字段,值对应租户所在的区域(比如"US"、"EU"、"AP"等,需确认租户实际地理位置)。修改后的请求体示例:

    var filter = new
    {
        Requests = new[] { 
            new {
                EntityTypes = new[] { "listItem" },
                Query = new
                {
                    QueryString = "Pio*"
                },
                Region = "US" // 替换为租户实际区域
            }
        }
    };
    
  2. 确认应用权限配置
    确保Azure AD应用已添加并授予SearchQuery.Read.All应用权限(需管理员同意),这是应用权限调用Search API的必要权限。

  3. 验证区域正确性
    如果添加Region后仍报错,需确认租户的实际区域:可通过Azure门户查看租户的地理位置,或调用Graph API的/organization接口获取相关信息辅助判断。

  4. 使用Microsoft Graph SDK简化调用
    建议替换原生HttpClient调用为Microsoft Graph SDK,SDK会自动处理部分参数校验和请求格式,减少手动构建请求的错误。示例代码(应用权限模式):

    var scopes = new[] { "https://graph.microsoft.com/.default" };
    var clientSecretCredential = new ClientSecretCredential(tenantName, clientId, clientSecret);
    var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
    
    var searchRequest = new SearchRequestObject
    {
        Requests = new List<SearchRequest>
        {
            new SearchRequest
            {
                EntityTypes = new List<EntityType> { EntityType.ListItem },
                Query = new SearchQuery
                {
                    QueryString = "Pio*"
                },
                Region = "US"
            }
        }
    };
    
    var result = await graphClient.Search.Query.PostAsync(searchRequest);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:35:24