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

.NET Core 6中WCF引用报ArrayTypeMismatchException错误如何修复?

问题分析与解决方案

问题重现

使用Visual Studio的SvcUtil工具基于WSDL生成客户端引用后,在.NET Core 6环境下,调用生成的GetBindingForEndpoint方法时,执行result.Elements.Add(httpsBindingElement);抛出System.ArrayTypeMismatchException,异常信息为"Attempted to access an element as a type incompatible with the array."。

生成的代码片段:

private static Binding GetBindingForEndpoint()
{
    CustomBinding result = new();
    result.Elements.Add(new TextMessageEncodingBindingElement(){
        MessageVersion = MessageVersion.CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, AddressingVersion.None)
    });
    HttpsTransportBindingElement httpsBindingElement = new()
    {
        AllowCookies = true,
        MaxBufferSize = int.MaxValue,
        MaxReceivedMessageSize = int.MaxValue
    };
    result.Elements.Add(httpsBindingElement);

    return result;
}

可能的原因

  1. .NET Core WCF集合实现特性:虽然HttpsTransportBindingElement和TextMessageEncodingBindingElement都是BindingElement的子类,但.NET Core中CustomBinding.Elements集合的底层数组存在隐式类型约束,直接添加子类实例时触发类型不匹配。
  2. 程序集版本冲突:若项目同时引用了.NET Framework的WCF旧程序集和.NET Core的WCF NuGet包,会导致BindingElement及其子类来自不同程序集,CLR会判定类型不兼容,即使表面存在继承关系。

解决方案

方案1:通过CustomBinding构造函数传入绑定元素列表

避免直接操作Elements集合,改用CustomBinding构造函数一次性传入所有绑定元素,这是.NET Core WCF推荐的用法:

private static Binding GetBindingForEndpoint()
{
    var bindingElements = new List<BindingElement>
    {
        new TextMessageEncodingBindingElement()
        {
            MessageVersion = MessageVersion.CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, AddressingVersion.None)
        },
        new HttpsTransportBindingElement()
        {
            AllowCookies = true,
            MaxBufferSize = int.MaxValue,
            MaxReceivedMessageSize = int.MaxValue
        }
    };
    return new CustomBinding(bindingElements);
}

方案2:显式转换为BindingElement类型

若需保留原代码结构,可尝试将子类实例显式转换为BindingElement后添加:

result.Elements.Add((BindingElement)httpsBindingElement);

方案3:修复程序集引用

确保项目仅引用.NET Core对应的WCF NuGet包:

  • 移除对.NET Framework的System.ServiceModel.dll等旧程序集的引用
  • 添加所需的.NET Core WCF NuGet包:
    • System.ServiceModel.Primitives
    • System.ServiceModel.Http
    • System.ServiceModel.Security

验证方法

修改代码后重新生成项目,调用客户端方法确认异常是否消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:45:13