Search code examples
c#asp.netmicrosoft-graph-apimicrosoft-graph-sdks

GraphServiceClient filter issue


I followed this page to setup a MicrosoftGraphProvider: http://www.keithmsmith.com/get-started-microsoft-graph-api-calls-net-core-3/

This is working correctly, as I am able to get a list of all of my users with the following request.

var user = await _graphServiceClient.Users.Request().GetAsync();

However, I don't always want all of the users returned, so I have a filter on a user by email.

The example says to do this

var user = await _graphServiceClient.Users[email].Request().GetAsync();

But this always results in user not found, even if I pass a valid email from the response of all users.

So I tried to build a filter, and do it this way.

var test = await _graphServiceClient.Users["$filter=startswith(mail,'test@email.com')"].Request().GetAsync();

var test = await _graphServiceClient.Users["$filter=(startswith(mail,'test@email.com'))"].Request().GetAsync();

Both of these returned the error:

Status Code: BadRequest
Microsoft.Graph.ServiceException: Code: BadRequest
Message: The $filter path segment must be in the form $filter(expression), where the expression resolves to a boolean.

This filter works fine when I use it in Postman calling the url directly. But I am trying to use their sdk and it is not working as expected.

What is wrong with this filter query?


Solution

  • $filter should be specified in Filter method. The article you followed does not reflect the current API.

    var users = await _graphServiceClient.Users
    .Request()
    .Filter("startswith(mail,'test@email.com')")
    .GetAsync();
    

    For SDK v5:

    var result = await _graphServiceClient.Users.GetAsync((rc) =>
    {
        rc.QueryParameters.Filter = "startswith(mail,'test@email.com')";
    });
    

    Check documentation