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

.NET 8与Microsoft.Identity.Web 2.x升级后:无法加载ITokenAcquisition类型

解决.NET 8 + Microsoft.Identity.Web 2.x中ITokenAcquisition类型加载失败的问题

问题原因

升级到Microsoft.Identity.Web 2.x后,令牌获取相关的服务注册逻辑发生调整,原1.x版本的链式调用方式可能无法正确注册ITokenAcquisition接口;同时可能存在项目依赖版本冲突或旧程序集残留,导致运行时无法找到该类型。

解决方案

1. 统一升级相关NuGet包

确保项目中所有与Microsoft.Identity.Web相关的包(如Microsoft.Identity.Web、Microsoft.Identity.Web.UI等)都升级到一致的2.x版本,避免版本冲突。可通过命令行执行:

dotnet add package Microsoft.Identity.Web --version 2.16.0
dotnet add package Microsoft.Identity.Web.UI --version 2.16.0

2. 调整身份验证服务配置代码

修改原有的身份验证注册逻辑,确保ITokenAcquisition被正确注册:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("Basic", null)
    .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAd"))
    // 显式添加令牌获取服务
    .AddTokenAcquisition()
    // 配置SharePoint下游API(替换为你的实际配置节点)
    .AddDownstreamApi("SharePoint", configuration.GetSection("AzureAd:SharePoint"))
    .AddDistributedTokenCaches();

若需保留原EnableTokenAcquisitionToCallDownstreamApi调用,确保链式逻辑完整:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("Basic", null)
    .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(sharepointScopes)
    .AddDistributedTokenCaches();

3. 清理并重新构建项目

删除项目的bin和obj文件夹,清理旧程序集残留,再重新构建项目,避免旧版本文件干扰。

4. 验证依赖注入正确性

检查SharePointClientContextFactory类中对ITokenAcquisition的引用,确保命名空间为Microsoft.Identity.Web,且构造函数注入方式正确:

using Microsoft.Identity.Web;

public class SharePointClientContextFactory : ISharePointClientContextFactory
{
    private readonly ITokenAcquisition _tokenAcquisition;

    public SharePointClientContextFactory(ITokenAcquisition tokenAcquisition)
    {
        _tokenAcquisition = tokenAcquisition;
    }

    // 其他业务实现代码
}

内容的提问来源于stack exchange,提问作者Liero

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:00:32