Подтвердить что ты не робот

Почему я возвращаю System.InvalidOperationException из вызова WSDL, но не от того же вызова к другой услуге?

Я создал услугу, чтобы получить информацию о стране разных клиентов, но при размещении службы я получаю это исключение. Я использую базовую привязку http.

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a 
WSDL export extension:   
  System.ServiceModel.Description.DataContractSerializerOperationBehavior
  contract: http://tempuri.org/:IReferenceDataService ----> 
     System.Runtime.Serialization.InvalidDataContractException: 
     Type 'Pariwaar.BusinessObject.CountryBO' cannot be serialized. 
     Consider marking it with the DataContractAttribute attribute, 
     and marking all of its members you want serialized with the 
     DataMemberAttribute attribute. See the Microsoft .NET Framework 
     documentation for other supported types.
   at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
   at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
   at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
   at System.Runtime.Serialization.DataContract.GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
   at System.Runtime.Serialization.DataContractSet.GetDataContract(Type clrType)
   at System.Runtime.Serialization.DataContractSet.GetItemTypeDataContract(CollectionDataContract collectionContract)
   at System.Runtime.Serialization.DataContractSet.AddCollectionDataContract(CollectionDataContract collectionDataContract)
   at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
   at System.Runtime.Serialization.DataContractSet.Add(Type type)
   at System.Runtime.Serialization.XsdDataContractExporter.Export(Type type)
   at System.ServiceModel.Description.MessageContractExporter.ExportType(Type type, String partName, String operationName, XmlSchemaType& xsdType)
   at System.ServiceModel.Description.DataContractSerializerMessageContractExporter.ExportBody(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessage(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessageContract()
   at System.ServiceModel.Description.DataContractSerializerOperationBehavior.System.ServiceModel.Description.IWsdlExportExtension.ExportContract(WsdlExporter exporter, WsdlContractConversionContext contractContext)
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   --- End of inner ExceptionDetail stack trace ---
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   at System.ServiceModel.Description.WsdlExporter.CallExportContract(WsdlContractConversionContext contractContext)
   at System.ServiceModel.Description.WsdlExporter.ExportContract(ContractDescription contract)
   at System.ServiceModel.Description.WsdlExporter.ExportEndpoint(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName)
   at System.ServiceModel.Description.WsdlExporter.ExportEndpoints(IEnumerable`1 endpoints, XmlQualifiedName wsdlServiceQName)
   at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
   at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.Get(Message message)
   at SyncInvokeGet(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

У меня есть businessobject[datamember] в другом проекте. Я назвал его dll здесь.

Вы можете просмотреть мой класс

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Pariwaar.BusinessObject;
using Pariwaar.DataAccessLayer;

namespace Pariwaar.WCFServices.SVC
{
    // NOTE: If you change the class name "ReferenceDataService" here, you must also update the reference to "ReferenceDataService" in Web.config.
    public class ReferenceDataService : IReferenceDataService
    {
        ReferenceData objDAL = new ReferenceData();

        public List<CountryBO> GetCountry()
        { return objDAL.GetCountry(); }

        public List<StateBO> GetState(int CountryId)
        { return objDAL.GetState(CountryId); }

        public List<CityBO> GetCity(int StateId)
        { return objDAL.GetCity(StateId); }
    }
}

Почему это нормально работает с другой службой WCF, но дает мне ошибку с другой услугой?

4b9b3361

Ответ 1

Ну, ошибка довольно ясна:

System.Runtime.Serialization.InvalidDataContractException: Тип 'Pariwaar.BusinessObject.CountryBO' не может быть сериализовано. Рассмотрите маркировку он с DataContractAttributeатрибута и маркировки всех его членов, которых вы хотите сериализовать с помощью Атрибут DataMemberAttribute. Видеть Microsoft.NET Framework документация для других поддерживаемых типы.

Очевидно, вы используете тип данных Pariwaar.BusinessObject.CountryBO как параметр или возвращаемое значение для одного из ваших методов службы WCF, но этот класс не имеет атрибута [DataContract].

См. документы MSDN в Использование Контрактов данных, чтобы узнать о контрактах с данными и о том, как сделать ваши объекты пригодными для использования WCF. См. Этот пост в блоге - Основы WCF: Контракты данных для другого представления по той же теме.

Все сложные типы (например, класс) должны быть помечены [DataContract], все поля, которые вы хотите включить в свои сообщения WCF с помощью [DataMember]:

[DataContract]
class Pariwaar.BusinessObject.CountryBO
{
   [DataMember]
   string CountryName { get; set; }

   [DataMember]
   string CountryCurrency { get; set; }

   [DataMember]
   string CountryISOCode { get; set; }

   ........
}

Марк

Ответ 2

Привет, я столкнулся с той же проблемой, потому что на объекте CountryBO не было конструктора по умолчанию.

Ответ 3

Эта ошибка может возникнуть в случае ошибки, мы использовали тип, который не был сохранен в контракте и мог использоваться в List < > или общедоступной переменной другого DataContract

HydTechie