简体   繁体   English

SharePoint 2019 Search REST API Is Returning 401 Unauthorized - When Called from C# Using Basic Authorization Request Header

[英]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. 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. My code calls the built-in SharePoint REST API in order to do searches and return results (the outside world will only be accessing my service).我的代码调用内置的 SharePoint REST API 进行搜索并返回结果(外界只会访问我的服务)。

I have no problem calling the SharePoint REST API from IE on that server.我从该服务器上的 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 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);
     }
    

Unfortunately, the results from the client.GetAsync are always as follows:不幸的是,client.GetAsync 的结果总是如下:

INFO 2021-01-07 01:24:18 StatusCode: 401, ReasonPhrase: 'Unauthorized' , Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers: { Server: 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; 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 Date: Thu, 07 Jan 2021 18:24:18 GMT Content-Length: 0 } RequireReadOnly 日期:2021 年 1 月 7 日星期四 18:24:18 GMT 内容长度:0 }

I have tried passing all SharePoint accounts I have, and all of them have given me the same 401.我已经尝试通过我拥有的所有 SharePoint 帐户,并且所有这些帐户都给了我相同的 401。

Any insight into resolving this would be much appreciated.任何解决此问题的见解将不胜感激。

I was able to find a solution for this.我能够找到解决方案。 The most important line is the NetworkCredential one.最重要的一行是 NetworkCredential 行。 I tried many other approaches, but this is the only one that worked for me.我尝试了许多其他方法,但这是唯一对我有用的方法。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM