我该如何调用外部wcf Web服务?

时间:2014-12-17 11:13:57

标签: c# web-services proxy service-reference

通过服务参考向项目添加了外部Web服务。是否有必要对其进行一些额外的操作,或者Web服务提供的方法和属性是否足够? 这是它的样子:

//Classes from web service
HHserviceClient h = new HHserviceClient();
HHPostPropertyRequest r = new HHPostPropertyRequest
  {
    //Web service properties
    Amenities = c.Amenities,
    ....
    MobileNo = c.MobileNo
  };
  //Method from web service
 h.PostProperty(r);

问题是当HHserviceClient调用时发生NullReference异常,这就是为什么我感到困惑 - 我应该调用像HttpClient这样的任何.Net类来做一些额外的工作。我之前从未做过任何与外部wcf网络服务有关的工作,所以我对此并不熟悉并提出建议。

更新

      var rq = new HHPostPropertyRequest
                    {
                        Amenities = c.Amenities,
                        Area = c.Area,
                        BathRooms = c.BathRooms,
                        Bedrooms = c.Bedrooms,
                        City = c.City,
                        Company = c.Company,
                        Contact = c.Contact,
                        Country = c.Country,
                        CustomerID = 1000,
                        Description = c.Description,
                        Email = c.Email,
                        LandLineNo = c.LandLineNo,
                        Lattitude = c.Lattitude,
                        Location = c.Location,
                        Longitude = c.Longitude,
                        MobileNo = c.MobileNo
                    };
                BasicHttpBinding myBinding = new BasicHttpBinding();
                EndpointAddress myEndpoint = new EndpointAddress("http://198.38.94.85/hhsvc/hhservice.svc/postproperty"); 
                ChannelFactory<IHHservice> myChannelFactory = new ChannelFactory<IHHservice>(myBinding, myEndpoint);
                IHHservice HHservice = myChannelFactory.CreateChannel();
                var result = HHservice.PostProperty(rq);
                ((IClientChannel)HHservice).Close();
                myChannelFactory.Close();

1 个答案:

答案 0 :(得分:2)

您可以尝试使用Channel工厂吗?它没有使用生成的配置等。

            var r = new Object()
            //define binding 
            //assume your binding using basicHttp, change it if you are using something else
            BasicHttpBinding myBinding = new BasicHttpBinding();           

            //define endpoint url              
            EndpointAddress myEndpoint = new EndpointAddress("http://localhost:11234/HHservice.svc"); //change to real endpoint 

            //Use channle factory instead of generated one
            ChannelFactory<IHHservice> myChannelFactory = new ChannelFactory<IHHservice>(myBinding, myEndpoint); //Change to you WCF interface
            IHHservice HHservice= myChannelFactory.CreateChannel();

            //and call it            
            var result = HHservice.PostProperty(r); //input to your method

            ((IClientChannel)HHservice).Close();
            myChannelFactory.Close();