![](/img/trans.png)
[英]Error when use link from Sharepoint with C# ( (401) unauthorized )
[英]SharePoint 2019 Search REST API Is Returning 401 Unauthorized - When Called from C# Using Basic Authorization Request Header
I have my own C# Web API service (targeting .NET 5.0) that is sitting on the same server where an on-premise SharePoint 2019 is located. 我的代碼調用內置的 SharePoint REST API 進行搜索並返回結果(外界只會訪問我的服務)。
我從該服務器上的 IE 調用 SharePoint REST API 沒有問題。
Within my Web API service (https) I call the SharePoint Rest service (http) using the same url that worked in IE
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(sharePointSearchServiceBaseUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("account:password");
string val = System.Convert.ToBase64String(plainTextBytes);
client.DefaultRequestHeaders.Add("Authorization", "Basic " + val);
HttpResponseMessage response = await client.GetAsync("search/query?querytext='(oil*)'&rowlimit=100");
if (response.IsSuccessStatusCode)
{
var objResponse = response.Content.ReadAsStringAsync().Result;
return Content(objResponse);
}
不幸的是,client.GetAsync 的結果總是如下:
INFO 2021-01-07 01:24:18 狀態碼: 401,ReasonPhrase:“未授權” ,版本:1.1,內容:System.Net.Http.HttpConnectionResponseContent,標頭:{服務器:Microsoft-IIS/10.0 SPRequestGuid:47049f9f-8244 -1032-40ac-07df48a24632 request-id: 47049f9f-8244-1032-40ac-07df48a24632 X-Frame-Options: SAMEORIGIN SPRequestDuration: 6 SPIisLatency: 2 WWW-Authenticate: NTLM X-Powered-By: ASP.NET MicrosoftSharePointTeamServices: 16.0.0.10368 X -Content-Type-Options:nosniff X-MS-InvokeApp:1; RequireReadOnly 日期:2021 年 1 月 7 日星期四 18:24:18 GMT 內容長度:0 }
我已經嘗試通過我擁有的所有 SharePoint 帳戶,並且所有這些帳戶都給了我相同的 401。
任何解決此問題的見解將不勝感激。
我能夠找到解決方案。 最重要的一行是 NetworkCredential 行。 我嘗試了許多其他方法,但這是唯一對我有用的方法。
using (var handler = new HttpClientHandler())
{
handler.Credentials = new NetworkCredential(account, password, domain);
using (var client = new HttpClient(handler))
{
var requri = new Uri("http://localhost:30001/_api/search/query?querytext='(oil*)'&rowlimit=100");
HttpResponseMessage response = await client.GetAsync(requri);
if (response.IsSuccessStatusCode)
{
var objResponse = response.Content.ReadAsStringAsync().Result;
_logger.LogInformation("Results are: " + objResponse);
return Content(objResponse);
}
else
{
_logger.LogInformation("Sharepoint service call - was NOT successful");
_logger.LogInformation(response.ToString());
return null;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.