简体   繁体   中英

Microsoft Graph API SDK BatchRequest -Filter by userprincipalname returning empty

I am trying to pull multiple users from Azure AD using microsoft graph api with batchrequest with Dot Net Core Microsoft.Graph.Beta SDK using filter by userprincipalname.

 var batchRequestContent = new BatchRequestContent();

 var queryOptions = new List<QueryOption>()
            {

                new QueryOption("$filter",$"userprincipalname eq '{email}'"),
                new QueryOption("$count","true"),
                new QueryOption("$select","id,mail")
            };

var request = client.Users.Request(queryOptions)       
                .Header("ConsistencyLevel", "Eventual")
                .Top(1);

var requestId = batchRequestContent.AddBatchRequestStep(request);
                emailWithRequestIds.Add(requestId, email);

var response = await 
               client.Batch.Request().PostAsync(batchRequestContent);

var responseList = await response.GetResponsesAsync();

  foreach (var key in responseList)
 {

  var email = emailWithRequestIds[key.Key];
  if (key.Value.StatusCode == HttpStatusCode.NotFound)
    {
       emailDictionary.Add(email, null);
    }
   else
    {
      key.Value.EnsureSuccessStatusCode();
      var responseContent = await key.Value.Content.ReadAsStringAsync();
      var parsedResponse = ValidateBatchResponse(responseContent, 
                           email);

      if (parsedResponse.Exists == true)
      {                             
       emailDictionary.Add(email,parsedResponse.Email);
      }
       else
       {
        emailDictionary.Add(email, null);
       }
     }
 }

The same request to users endpoint without batch is returning data, while inside batchrequest it is returning empty. Is there any limitation that batch endpoint to work with userPrincipalName while using sdk?

There is indeed a limitation on the batch size. As stated here :

JSON batch requests are currently limited to 20 individual requests.

It doesn't have anything to do with your $filter. Because that works flawless with the users endpoint.

UPDATE: After seeing the code, I think the issue lies in casting the HttpResponse content to a Microsoft.Graph.User . If the casting is not done correctly, it will show an empty Microsoft.Graph.User .

The following worked for me:

var responseList = await response.GetResponsesAsync();
foreach (var resp in responseList) 
{
    var userString = await resp.Value.Content.ReadAsStringAsync(); 
    var userCollection = await System.Text.Json.JsonSerializer.Deserialize<GraphServiceUsersCollectionResponse>(userString); 
    var user = userCollection.Value.SingleOrDefault();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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