MSAL函数缺失:FirstOrDefault(),库安装版本问题求助
Users.FirstOrDefault() in MSAL Preview Version Hey there! I’ve run into this exact issue before when working with MSAL’s preview builds—let’s break down what’s going on and how to fix it:
Why the Users Property Is Missing
When you installed MSAL with Install-Package Microsoft.Identity.Client -Pre, you grabbed a preview version of the library. In newer MSAL.NET releases (especially v4+), the old Users collection on PublicClientApplication has been deprecated and removed in favor of async, account-focused APIs. The official guide might not have caught up to the preview builds yet, which is why the example code doesn’t match what you’re seeing.
How to Get the Logged-In Account & Token
Replace the old Users.FirstOrDefault() code with the modern async approach using GetAccountsAsync():
- First, add
using System.Linq;at the top of your file to access LINQ methods likeFirstOrDefaultAsync(). - Update your account retrieval and token acquisition logic:
// Get the first logged-in account (async is required now) var account = await PublicClientApp.GetAccountsAsync().FirstOrDefaultAsync(); if (account != null) { // Acquire a silent token for the existing account var tokenResult = await PublicClientApp.AcquireTokenSilent(scopes, account) .ExecuteAsync(); // Use the retrieved token via tokenResult.AccessToken }
Bonus Tip: Use Stable MSAL for Better Guide Alignment
If you’re just getting started with Azure AD auth, I’d recommend switching to the stable MSAL release to avoid API mismatches with the official guide. First uninstall the preview package:
Uninstall-Package Microsoft.Identity.Client
Then install the stable version:
Install-Package Microsoft.Identity.Client
This way, the example code from the guide will line up perfectly with the library’s API.
内容的提问来源于stack exchange,提问作者N3rdB0mber

