C# REST搜索API远程服务器返回错误:(401)未经授权
我使用本教程创建了一个控制台应用程序: 当然,有一些不同之处,在我的控制台应用程序中,我想对搜索api进行rest调用 阅读以下内容:授予应用程序主体权限,而不是像我使用的示例中那样使用租户管理:C# REST搜索API远程服务器返回错误:(401)未经授权,c#,rest,sharepoint,C#,Rest,Sharepoint,我使用本教程创建了一个控制台应用程序: 当然,有一些不同之处,在我的控制台应用程序中,我想对搜索api进行rest调用 阅读以下内容:授予应用程序主体权限,而不是像我使用的示例中那样使用租户管理: <AppPermissionRequests> <AppPermissionRequest Scope="https://sharepoint/search" Right="QueryAsUserIgnoreAppPrincipal" /> </AppPe
<AppPermissionRequests>
<AppPermissionRequest Scope="https://sharepoint/search" Right="QueryAsUserIgnoreAppPrincipal" />
</AppPermissionRequests>
我想知道问题可能是什么QueryAsUserIgnoreAppPrincipal权限完全按照它所说的做。。。它以当前用户身份查询搜索,忽略应用权限。您的代码获得仅应用程序权限,该权限不提供用户信息。我希望在这种情况下401未经授权 请记住,搜索查询是根据用户进行安全调整的。您可以尝试对仅应用程序上下文使用租户读取权限,删除QueryAsUserIgnoreAppOnly,但我还没有尝试查看这是否有效。更好的选择可能是简单地使用SharePointOnlineCredentials类来指定一个有足够权限访问该内容的用户(如果该用户无权访问该内容,则该内容将不会显示在搜索结果中)
<xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Sites"
type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<appSettings>
<add key="ClientId" value="xx-1c6c-45e7-8a2a-7364a705c836"/>
<add key="ClientSecret" value="+xx="/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<Sites>
<add key="site1" value="https://xx.sharepoint.com/sites/developersitecollection"/>
</Sites>
</configuration>
static void Main(string[] args)
{
var config = (NameValueCollection)ConfigurationManager.GetSection("Sites");
foreach (var key in config.Keys)
{
Uri siteUri = new Uri(config.GetValues(key as string)[0]);
using (ClientContext clientContext = new ClientContext(siteUri))
{
string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
string accessToken =
TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal,
siteUri.Authority, realm).AccessToken;
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(siteUri +"/_api/search/query?querytext=%27*.pptx%27");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
StreamReader reader = new StreamReader(endpointResponse.GetResponseStream());
var searchXml = new XmlDocument();
searchXml.LoadXml(reader.ReadToEnd());
}
}
}