Using nextLink to retrieve email messages with the Microsoft Graph .NET Core SDK

Dan Wahlin 21 Reputation points Microsoft Employee
2021-08-04T17:54:52.693+00:00

What is the best practice way to use nextLink with the .NET Core SDK and Microsoft Graph when working with email messages? I'm currently doing the following to retrieve messages and then move forward through them:

public async Task<(IEnumerable<Message> Messages, int Skip)> GetUserMessagesPage(int pageSize, int skip = 0)
{
    var pagedMessages = await _graphServiceClient.Me.Messages
            .Request()
            .Select(msg => new
            {
                msg.Subject,
                msg.Body,
                msg.BodyPreview,
                msg.ReceivedDateTime
            })
            .Top(pageSize)
            .Skip(skip)
            .OrderBy("receivedDateTime")
            .GetAsync();

    var skipValue = pagedMessages
        .NextPageRequest?
        .QueryOptions?
        .FirstOrDefault(
            x => string.Equals("$skip", WebUtility.UrlDecode(x.Name), StringComparison.InvariantCultureIgnoreCase))?
        .Value ?? "0";

    _logger.LogInformation($"skipValue: {skipValue}");

    return (Messages: pagedMessages, Skip: int.Parse(skipValue));
}

While this works fine, I'd prefer to use the value in @odata.nextLink. I tried doing something like the following but get an error about the token not being sent when SendAsync() is called (the nextLink value is hard-coded in this simple example but I can retrieve it from pagedMesssages.AdditionalData):

var httpRequest = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/messages?%24select=subject%2cbody%2cbodyPreview%2creceivedDateTime&%24orderby=receivedDateTime&%24top=5&%24skip=5");
var response = await _graphServiceClient.HttpProvider.SendAsync(httpRequest);

The _graphServiceClient object is the same one used with the first code shown above which works perfectly fine. It's injected automatically (full code at https://github.com/DanWahlin/DotnetCoreRazor-MicrosoftGraph/blob/main/Startup.cs). But, going through the _graphServiceClient.HttpProvider doesn't seem to do what I was expecting given that no token is sent. What's the best way to use nextLink to call and get the next set of messages with the .NET Core SDK?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,510 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Dan Wahlin 21 Reputation points Microsoft Employee
    2021-08-28T18:11:54.167+00:00

    Ended up going with the following (thanks to Andrew's recommendation):

    UserMessagesCollectionRequest messagesCollectionRequest = 
       new UserMessagesCollectionRequest(nextPageLink, _graphServiceClient, null);
    var pagedMessages = await messagesCollectionRequest.GetAsync();
    
    1 person found this answer helpful.
    0 comments No comments