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

使用Azure Identity SDK 1.10.4时ClientSecretCredential报Method not found错误

Azure Identity ClientSecretCredential认证失败:MissingMethodException(JsonObjectInfoValues`1.set_ObjectCreator)

问题详情

使用Azure Identity .NET SDK 1.10.4的ClientSecretCredential类生成令牌读取Blob存储,严格遵循官方容器内列出Blob的示例代码,但在执行await foreach遍历Blob分页结果时抛出错误,错误栈如下:

Azure.Identity.AuthenticationFailedException: ClientSecretCredential authentication failed: Method not found: 'Void System.Text.Json.Serialization.Metadata.JsonObjectInfoValues`1.set_ObjectCreator(System.Func`1<!0>)'.
 ---&gt; System.MissingMethodException: Method not found: 'Void System.Text.Json.Serialization.Metadata.JsonObjectInfoValues`1.set_ObjectCreator(System.Func`1<!0>)'.
   at Microsoft.Identity.Client.Platforms.net6.MsalJsonSerializerContext.get_InstanceDiscoveryResponse()
   at Microsoft.Identity.Client.Platforms.net6.MsalJsonSerializerContext.GetTypeInfo(Type type)
   at System.Text.Json.JsonSerializer.GetTypeInfo(JsonSerializerContext context, Type inputType)
   at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerContext context)
   at Microsoft.Identity.Client.Utils.JsonHelper.DeserializeFromJson[T](String json)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func`2 onBeforePostRequestData)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.DiscoverAadInstanceAsync(Uri endpoint, RequestContext requestContext)
   at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.SendInstanceDiscoveryRequestAsync(Uri authority, RequestContext requestContext)
   at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.FetchAllDiscoveryMetadataAsync(Uri authority, RequestContext requestContext)
   at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.GetMetadataAsync(Uri authority, RequestContext requestContext)
   at Microsoft.Identity.Client.Instance.Discovery.InstanceDiscoveryManager.FetchNetworkMetadataOrFallbackAsync(RequestContext requestContext, Uri authorityUri)
   at Microsoft.Identity.Client.Instance.Discovery.InstanceDiscoveryManager.GetMetadataEntryAsync(AuthorityInfo authorityInfo, RequestContext requestContext, Boolean forceValidation)
   at Microsoft.Identity.Client.Instance.AuthorityManager.RunInstanceDiscoveryAndValidationAsync()
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.GetAccessTokenAsync(CancellationToken cancellationToken, ILoggerAdapter logger)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters, CancellationToken cancellationToken)
   at Azure.Identity.AbstractAcquireTokenParameterBuilderExtensions.ExecuteAsync[T](AbstractAcquireTokenParameterBuilder`1 builder, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientCoreAsync(String[] scopes, String tenantId, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientAsync(String[] scopes, String tenantId, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.ClientSecretCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
   at Azure.Identity.ClientSecretCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
   at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetHeaderValueFromCredentialAsync(TokenRequestContext context, Boolean async, CancellationToken cancellationToken)
   at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetHeaderValueAsync(HttpMessage message, TokenRequestContext context, Boolean async)
   at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetHeaderValueAsync(HttpMessage message, TokenRequestContext context, Boolean async)
   at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AuthenticateAndAuthorizeRequestAsync(HttpMessage message, TokenRequestContext context)
   at Azure.Storage.StorageBearerTokenChallengeAuthorizationPolicy.AuthorizeRequestInternal(HttpMessage message, Boolean async)
   at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.InnerProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.RedirectPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
   at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
   at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
   at Azure.Storage.Blobs.ContainerRestClient.ListBlobFlatSegmentAsync(String prefix, String marker, Nullable`1 maxresults, IEnumerable`1 include, Nullable`1 timeout, CancellationToken cancellationToken)
   at Azure.Storage.Blobs.BlobContainerClient.GetBlobsInternal(String marker, BlobTraits traits, BlobStates states, String prefix, Nullable`1 pageSizeHint, Boolean async, CancellationToken cancellationToken)
   at Azure.Storage.Blobs.Models.GetBlobsAsyncCollection.GetNextPageAsync(String continuationToken, Nullable`1 pageSizeHint, Boolean async, CancellationToken cancellationToken)
   at Azure.Storage.StorageCollectionEnumerator`1.StorageAsyncPageable.AsPages(String continuationToken, Nullable`1 pageHintSize)+MoveNext()
   at Azure.Storage.StorageCollectionEnumerator`1.StorageAsyncPageable.AsPages(String continuationToken, Nullable`1 pageHintSize)+System.Threading.Tasks.Sources.IValueTaskSource&lt;System.Boolean&gt;.GetResult()

使用的代码如下:

var tenantId = tenantid;
var clientId = ClientId;
var clientSecret = clientSecret;
var credential = new Azure.Identity.ClientSecretCredential(
    tenantId,
    clientId,
    clientSecret,
    new TokenCredentialOptions
    {
        AuthorityHost = new Uri("https://login.microsoftonline.com")
    });

Console.WriteLine($"credential object {credential}");

var blobServiceClient = new 
    BlobServiceClient(new Uri("https://<storageaccountname>.blob.core.windows.net"),credential);

Console.WriteLine(blobServiceClient);

var blobcontainerClient = blobServiceClient.GetBlobContainerClient("containername");

Console.WriteLine(blobcontainerClient);

int? segmentSize = null;

// Call the listing operation and return pages of the specified size.
var resultSegment = blobcontainerClient.GetBlobsAsync()
        .AsPages(default, segmentSize);

// Enumerate the blobs returned for each page.

try
{
    // *** Exception occurs at this await foreach line: ***
    await foreach (Azure.Page<BlobItem> blobPage in resultSegment)
    {
        foreach (BlobItem blobItem in blobPage.Values)
        {
            Console.WriteLine("Blob name: {0}", blobItem.Name);
        }

        Console.WriteLine("all complete");
    }
}
catch(Exception ex)
{
    Console.WriteLine(ex);
}

错误原因

该错误是System.Text.Json版本不兼容导致的:
Azure Identity SDK 1.10.4依赖的Microsoft.Identity.Client(MSAL)库使用了.NET 6+版本System.Text.Json中的JsonObjectInfoValues<T>.ObjectCreator属性setter方法,而你的项目引用的System.Text.Json版本过低(如.NET 5及以下,或NuGet包版本低于6.0),运行时无法找到该方法,从而触发MissingMethodException。

解决方案

方案1:升级项目.NET版本到6.0或更高

直接将项目目标框架切换为.NET 6/7/8,.NET 6及以上版本的System.Text.Json已内置该方法,无需额外调整NuGet包。

方案2:升级System.Text.Json NuGet包版本

若无法升级.NET版本,在NuGet包管理器中,将System.Text.Json包升级至6.0.0或更高版本,确保与MSAL依赖的版本匹配。

方案3:修复NuGet依赖冲突

检查项目依赖项,确认是否有其他库强制引用低版本System.Text.Json:

  • 在NuGet包管理器的"依赖项"视图中查看版本冲突
  • 使用PackageReference的Force属性强制指定高版本:
    <PackageReference Include="System.Text.Json" Version="6.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    

验证

修改后重新编译并运行项目,确认await foreach遍历Blob分页结果可正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:25:03