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

从Xamarin.Android迁移至.NET8后Web Service引用无法正常使用求助

.NET8中SOAP服务接口的实例化与调用方案
  • 直接使用ChannelFactory实例化接口
    .NET8添加SOAP服务引用后,默认生成WCF风格的服务接口,你可以通过ChannelFactory<T>创建接口实例,示例代码如下:

    using System.ServiceModel;
    using AXPackSlipService;
    
    // 根据原服务配置选择绑定类型,这里以BasicHttpBinding为例
    var binding = new BasicHttpBinding();
    var endpointAddress = new EndpointAddress("你的Web服务完整地址,如http://xxx/DeliveryNoteService.asmx");
    
    var channelFactory = new ChannelFactory<DeliveryNoteServiceSoap>(binding, endpointAddress);
    DeliveryNoteServiceSoap testService = channelFactory.CreateChannel();
    
    // 调用目标方法
    testService.getDeliveryNoteLines("参数1", "参数2", "参数3");
    
    // 使用完毕后关闭通道
    ((IClientChannel)testService).Close();
    

    注意:绑定类型需与原Xamarin项目保持一致,服务地址要确保可正常访问。

  • 封装类还原旧代码调用风格
    如果想完全沿用旧项目的调用方式,可以自行封装一个DeliveryNoteService类,内部处理WCF客户端的创建逻辑:

    using System.ServiceModel;
    using AXPackSlipService;
    
    public class DeliveryNoteService
    {
        private readonly DeliveryNoteServiceSoap _serviceClient;
    
        public DeliveryNoteService()
        {
            var binding = new BasicHttpBinding();
            var endpointAddress = new EndpointAddress("你的Web服务完整地址");
            var channelFactory = new ChannelFactory<DeliveryNoteServiceSoap>(binding, endpointAddress);
            _serviceClient = channelFactory.CreateChannel();
        }
    
        public void getDeliveryNoteLines(string param1, string param2, string param3)
        {
            _serviceClient.getDeliveryNoteLines(param1, param2, param3);
        }
    
        // 添加资源释放逻辑
        public void Dispose()
        {
            ((IClientChannel)_serviceClient)?.Close();
        }
    }
    

    之后就能像旧代码一样调用:

    using AXPackSlipService;
    
    DeliveryNoteService testService = new DeliveryNoteService();
    testService.getDeliveryNoteLines("参数1", "参数2", "参数3");
    testService.Dispose();
    
  • 额外注意事项

    • 确保项目已安装System.ServiceModel.Http NuGet包,这是.NET8中使用WCF客户端的必要依赖。
    • 如果服务有安全验证要求,需在绑定中配置对应的Credentials参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:49:58