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

.NET Core SSO服务提供商应用点击登录时抛出Sequence无元素异常求助

.NET Core SSO登录时抛出"Sequence contains no elements"异常的解决方法

异常明确指向调用First()时目标集合为空,具体是entityDescriptor.IdPSsoDescriptor.SingleSignOnServices或SingleLogoutServices没有元素。结合你的代码和配置,主要问题及解决方式如下:

1. 配置键名不匹配

你的appsettings.json中SAML元数据的配置键是zau_idpMetadata,但program.cs里读取的是configuration["Saml2:IdPMetadata"],键名不一致导致加载的元数据无效,进而服务集合为空。同时注意元数据URL末尾有多余空格,需要去除。

修正后的元数据读取代码:

entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(configuration["Saml2:zau_idpMetadata"].Trim()));

2. 未处理空集合情况

即使元数据加载正常,也无法保证IdP的元数据里一定包含SingleLogoutServices(部分IdP可能未启用注销服务),直接调用First()会在集合为空时抛出异常。建议改用FirstOrDefault()并添加空判断,同时可 fallback到你在appsettings.json中预配置的地址。

修改后的完整配置代码:

builder.Services.Configure<Saml2Configuration>(saml2Configuration =>
{
    saml2Configuration.AllowedAudienceUris.Add(saml2Configuration.Issuer);

    var metadataUrl = configuration["Saml2:zau_idpMetadata"].Trim();
    var entityDescriptor = new EntityDescriptor();
    entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(metadataUrl));
    
    if (entityDescriptor.IdPSsoDescriptor != null)
    {
        // 处理单点登录地址
        var ssoService = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.FirstOrDefault();
        saml2Configuration.SingleSignOnDestination = ssoService?.Location 
            ?? configuration["Saml2:SingleSignOnDestination"];

        // 处理单点注销地址
        var sloService = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.FirstOrDefault();
        saml2Configuration.SingleLogoutDestination = sloService?.Location 
            ?? configuration["Saml2:SingleLogoutDestination"];

        saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
    }
    else
    {
        throw new Exception("IdPSsoDescriptor not loaded from metadata.");
    }
});

builder.Services.AddSaml2();

var app = builder.Build();

3. 验证元数据有效性

手动访问去除空格后的元数据URL https://saml.zau.edu/zau_idp/shibboleth,检查返回的XML中是否存在:

  • <md:SingleSignOnService>节点(对应SSO服务)
  • <md:SingleLogoutService>节点(对应注销服务)
    如果IdP元数据中确实没有这些节点,需要联系身份提供商确认服务配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:28:13