You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MSAL函数缺失:FirstOrDefault(),库安装版本问题求助

Fixing Missing 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():

  1. First, add using System.Linq; at the top of your file to access LINQ methods like FirstOrDefaultAsync().
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:15:12