使用Microsoft Graph API访问SharePoint时解决Invalid hostname for this tenancy错误
错误根源
你直接使用站点名称test-site-001作为Graph API请求中的站点标识符,不符合API的格式要求。Graph API无法仅通过站点名称确定对应的租户和站点上下文,因此抛出该错误。
解决方案
需要使用符合Graph API规范的站点标识符格式构造请求URL,以下是两种可行方法:
方法1:使用站点完整URL路径构造请求
直接在请求URL中指定租户的SharePoint域名和站点路径,格式为:https://graph.microsoft.com/v1.0/sites/{租户SharePoint域名}:/sites/{站点名称}:/drive/root/children
替换{租户SharePoint域名}为你的实际域名(比如contoso.sharepoint.com或contoso.onmicrosoft.com),修正后的代码示例:
const fetchOneDriveFiles = async () => { try { const tenantDomain = "your-tenant.sharepoint.com"; // 替换为你的租户SharePoint域名 const response = await fetch( `https://graph.microsoft.com/v1.0/sites/${tenantDomain}:/sites/test-site-001:/drive/root/children`, { headers: { Authorization: `Bearer ${accessToken}`, }, } ); if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } const data = await response.json(); setFiles(data.value); } catch (error) { console.error("获取文件失败:", error); } };
方法2:先获取站点ID,再用ID访问
如果不确定站点的完整域名,可以先调用API获取站点唯一ID,再用ID构造请求:
- 调用
GET https://graph.microsoft.com/v1.0/sites/{租户SharePoint域名}/sites/test-site-001获取站点详情,提取返回结果中的id字段 - 使用站点ID构造请求URL:
https://graph.microsoft.com/v1.0/sites/{站点ID}/drive/root/children
额外检查项
- 确认
test-site-001是站点的正确路径名称(即站点URL中的/sites/test-site-001部分) - 确保Azure AD授予的访问令牌包含
Sites.Read.All或Sites.ReadWrite.All权限,且权限已完成管理员同意(应用权限)或用户授权(委托权限) - 当前登录用户需拥有该SharePoint站点的访问权限
内容的提问来源于stack exchange,提问作者Ayesh Nipun
相关产品推荐
相关产品推荐

