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

.NET Core 6.0下SOAPCore接收string[]参数时InvalidCastException问题

问题原因

SOAPCore处理HTTP GET请求参数时,默认不会自动将重复查询参数(如?inputArray=300&inputArray=400)或逗号分隔字符串(如?inputArray=300,400)解析为string[]类型。它会把单个参数值识别为System.String,强制转换为string[]时就会抛出InvalidCastException。

解决方案

方案1:修改接口参数为字符串,内部拆分(简单直接)

将接口的string[]参数改为string,在方法内部手动拆分字符串为数组,适配逗号分隔的请求方式:

修改接口:

[ServiceContract]
public interface IYourService
{
    [OperationContract]
    [WebGet(UriTemplate = "ProcessArray?inputArray={inputArray}", ResponseFormat = WebMessageFormat.Xml)]
    string[] ProcessArray(string inputArray);
}

修改实现:

public class YourService : IYourService
{
    public string[] ProcessArray(string inputArray)
    {
        // 拆分逗号分隔的字符串为数组,移除空项
        string[] inputArraySplit = inputArray.Split(',', StringSplitOptions.RemoveEmptyEntries);
        
        List<string> result = new List<string>();
        foreach (string item in inputArraySplit)
        {
            string processedItem = "Processed: " + item;
            result.Add(processedItem);
        }

        return result.ToArray();
    }
}

请求URL使用逗号分隔格式:

http://localhost:5279/yourservice.asmx/ProcessArray?inputArray=300,400

方案2:启用ASP.NET Core模型绑定解析重复参数

如果需要支持重复参数名的请求方式(?inputArray=300&inputArray=400),在接口参数上添加[FromQuery]属性并启用WebGet:

修改接口:

[ServiceContract]
public interface IYourService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Xml)]
    string[] ProcessArray([FromQuery(Name = "inputArray")] string[] inputArray);
}

此时使用重复参数名的URL即可正常请求:

http://localhost:5279/yourservice.asmx/ProcessArray?inputArray=300&inputArray=400

注意事项

  • SOAPCore对HTTP GET的参数解析能力有限,因为SOAP协议本身基于XML POST请求。如果需要复杂参数处理,建议优先使用标准SOAP POST请求(传递XML格式的数组参数)。
  • 确保Program.cs中正确配置SOAPCore中间件,示例:
app.UseEndpoints(endpoints =>
{
    endpoints.UseSoapEndpoint<IYourService>("/yourservice.asmx", new SoapEncoderOptions());
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:12:58