I want to get the count for direct user membership of a group. This can be achieved with Advanced Queries. I'm using the Microsoft Graph SDK and this code to request it:
var url = client
.Groups[groupId]
.Members
.AppendSegmentToRequestUrl("microsoft.graph.user/$count");
var requestbuilder = new GroupRequestBuilder(url, client);
var result = await requestbuilder
.Request()
.Header("ConsistencyLevel", "eventual")
.GetAsync();
It should be the equivalent of this URL:
https://graph.microsoft.com/v1.0/groups/<groupId>/members/microsoft.graph.user/$count
with the header:
ConsistencyLevel = eventual
The request seems to go okay, but the response only includes the count in plain text. This is why JsonReader is throwing an error I think. So how can I get only this plain text result value?
I've tried adding select to the query to skip the JsonReader, but the lambda only accepts group properties...
await requestbuilder
.Request()
.Header("ConsistencyLevel", "eventual")
.Select(x => new { x })
.GetAsync();
I figured it out by going trough the Microsoft.Graph.Core sourcecode and docs. A reponse message is always deserialized what causes the problem in my case.
I've created a custom IResponseHandler
for a text/plain response message:
public class GraphPlainTextResponseHandler : IResponseHandler
{
public async Task<T> HandleResponse<T>(HttpResponseMessage response)
{
//Throw error if reponse is not successful
if (!response.IsSuccessStatusCode) throw new HttpResponseException(response.StatusCode);
//Throw error if response content-type is not of type text/plain
if (response.Content.Headers.ContentType.MediaType != "text/plain") throw new InvalidOperationException($"Incorrect Content-Type: {response.Content.Headers.ContentType.MediaType}");
return (T)Convert.ChangeType(await response.Content.ReadAsStringAsync(), typeof(T));
}
}
Then I created the request with this code:
var url = client.Groups[groupId].Members.AppendSegmentToRequestUrl("microsoft.graph.user/$count");
var baseRequest = new BaseRequest(url, client).WithResponseHandler(new GraphPlainTextResponseHandler());
baseRequest.Header("ConsistencyLevel", "eventual");
var result = await baseRequest.SendAsync<string>(null, CancellationToken.None);