I'm trying to search file on SharePoint using Graph API. Getting the correct result on Microsoft graph-explorer
but when I try with C# Getting error Status Code: 500
Reason Phrase:Internal Server Error
Response Details as below:
{
"error": {
"code": "System.NullReferenceException",
"message": "Object reference not set to an instance of an object.",
"innerError": {
"date": "2021-03-19T16:16:28",
"request-id": "f3092cda-b813-4507-928e-7e2de84fc88f",
"client-request-id": "f3092cda-b813-4507-928e-7e2de84fc88f"
}
}
}
C# Code I'm using
var searchTerm = "164377_07323_03122021_112659_TaxApp";
var headerStr = @"{{""requests"": [{{""entityTypes"": [""listItem""],""query"": {{""queryString"": ""{0}""}}}}]}}";
headerStr = string.Format(headerStr, searchTerm);
var headerJson = JsonConvert.SerializeObject(headerStr);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResponse.AccessToken);
var content = new StringContent(headerJson, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync("https://graph.microsoft.com/v1.0/search/query", content).Result;
var postResult = response.Content.ReadAsStringAsync().Result;
Any pointers where I'm going wrong?
Try using the below code. Looks like your code is getting serialized twice. So I just removed the serialization step and it worked.
var searchTerm = "164377_07323_03122021_112659_TaxApp";
var headerStr = @"{{""requests"": [{{""entityTypes"": [""listItem""],""query"": {{""queryString"": ""{0}""}}}}]}}";
headerStr = string.Format(headerStr, searchTerm);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResponse.AccessToken);
var content = new StringContent(headerStr, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync("https://graph.microsoft.com/v1.0/search/query", content).Result;
var postResult = response.Content.ReadAsStringAsync().Result;
You can always test the API requests using fiddler.