0

我在 wcf 中编写了一个返回对象的 Web 服务。但是当我从客户端代码调用它时,它不会返回任何对象。

我想返回的那个对象

[DataContract]
    public class OrderData
    {
        [DataMember]
        public List<ORDER_INFO> OrderInfoList { get; set; }
        [DataMember]
        public List<ORDER_PRODUCT_MAPPING> OrderProductMappingList { get; set; }
    }

My Service Interface 

[ServiceContract]
    public interface ISyncService
    {
        [OperationContract]
        OrderData InsertOrderData(decimal depotId);
    }

接口实现类

public class SyncService : ISyncService
    {
        readonly InceptaDbContext _db = new InceptaDbContext();

        public OrderData InsertOrderData(decimal depotId)
        {
            var orderData = new OrderData
            {
                OrderInfoList = new List<ORDER_INFO>(),
                OrderProductMappingList = new List<ORDER_PRODUCT_MAPPING>()
            };

            var orderList = _db.ORDER_INFO
                .Where(m => m.D_ID.Equals(depotId)&& m.STATUS.Equals("1"));
                            //.Where(m => m.STATUS.Equals("1"));
            foreach (var orderInfo in orderList)
            {
                orderData.OrderInfoList.Add(orderInfo);
                orderData.OrderProductMappingList.AddRange(
                    _db.ORDER_PRODUCT_MAPPING.Where(m => m.ORDER_ID.Equals
                                                             (orderInfo.ORDER_ID)));
            }

            foreach (var orderInfo in orderList)
            {
                orderInfo.STATUS = "2";
                _db.Entry(orderInfo).State = EntityState.Modified;
            }
            _db.SaveChanges();

                return orderData;


        }
    }

我的服务器网络配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
        <directoryBrowse enabled="true" />
  </system.webServer>
  <connectionStrings>
    <add name="InceptaDbContext" 
         connectionString="metadata=res://*/DbContext.Model1.csdl|res://*/DbContext.Model1.ssdl|res://*/DbContext.Model1.msl;provider=Oracle.DataAccess.Client;provider connection string=&quot;DATA SOURCE=localhost/InceptaMSFA;PASSWORD=bs23;PERSIST SECURITY INFO=True;USER ID=BS&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

我的客户端应用程序是 C# 主程序中的控制台应用程序

class Program
    {
        static void Main(string[] args)
        {
            var client = new SyncServiceClient();
            var db = new InceptaDbContext();


            var order = client.InsertOrderData(1.0m);

            foreach (var s in order.OrderInfoList)
            {
                db.ORDER_INFO.Add(new ConsumeDataSyncService.DbContext.ORDER_INFO
                                      {
                                          ORDER_ID = s.ORDER_ID,
                                          CH_ID = s.CH_ID,
                                          D_ID = s.D_ID,
                                          EMP_ID = s.EMP_ID,
                                          ORDER_DATE = s.ORDER_DATE,
                                          ORDER_TYPE = s.ORDER_TYPE,
                                          PAY_OPTION = s.PAY_OPTION,
                                          PRODUCT_COUNT = s.PRODUCT_COUNT,
                                          STATUS = "2"
                                      });
                Console.WriteLine(s.ORDER_ID +"Inserted");
            }

            foreach (var s in order.OrderProductMappingList)
            {
                var orderProductMapping = new ConsumeDataSyncService.DbContext.ORDER_PRODUCT_MAPPING
                                              {
                                                  ID = s.ID,
                                                  ORDER_ID = s.ORDER_ID,
                                                  P_CODE = s.P_CODE,
                                                  QUANTITY = s.QUANTITY
                                              };
                db.ORDER_PRODUCT_MAPPING.Add(orderProductMapping);
                Console.WriteLine(s.ID + "Inserted");
            }
            db.SaveChanges();
            Console.ReadKey();
        }
    }

and app.config 

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_ISyncService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:8092/SyncService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISyncService" contract="OrderSyncService.ISyncService" name="BasicHttpBinding_ISyncService" />
    </client>
  </system.serviceModel>
  <connectionStrings>
    <add name="InceptaDbContext" connectionString="metadata=res://*/DbContext.Model1.csdl|res://*/DbContext.Model1.ssdl|res://*/DbContext.Model1.msl;provider=Oracle.DataAccess.Client;provider connection string=&quot;DATA SOURCE=192.168.1.159/Incepta;PASSWORD=bs23;USER ID=BS&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

the error I got at the time of debugging

Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.

The underlying connection was closed: The connection was closed unexpectedly.

Server stack trace: 
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at ISyncService.InsertOrderData(Decimal depotId)
   at SyncServiceClient.InsertOrderData(Decimal depotId)

Inner Exception:
The underlying connection was closed: The connection was closed unexpectedly.
   at System.Net.HttpWebRequest.GetResponse()`enter code here`
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
4

3 回答 3

1

通常出现此错误,模型中似乎存在循环引用,因此无法序列化。启用跟踪以查看服务的日志,您可以在其中查看是什么异常导致服务意外关闭连接。

于 2013-03-21T12:34:34.290 回答
1

感谢所有给我时间的人....我已经解决了这个问题。在 OrderData 类中有两个属性,它们也是另一个类。所以我在属性中的类(ORDER_INFO 和 ORDER_PRODUCT_MAPPING)和 [DataMember] 中添加了类似 [DataContract] 的属性并解决了我的问题。

于 2013-03-22T05:32:11.203 回答
0

通过添加尝试

[Serializable,DataContract()]

在类名上方。

于 2013-03-21T11:07:25.147 回答