DataContract和WCF层级结构出现问题

4

我在我的WCF项目中遇到了一个对象问题。假设我有这个对象:

[DataContract(Name="ClassA")]
public class Person{
   //---attributes---
}

[DataContract(Name="ClassB")]
public class Men : Person{
  //---attributes---
}

当ClassB是ClassA的子类时,我有一个使用POST方法的方法:

[OperationContract]
[WebInvoke(UriTemplate= "Person", ResponseFormat = WebMessageFormat.Json, Method= "POST")]
public string PostPerson(Person person) {
    if(person is Men){
       //code...
    }
}

事情是这样的,我接收到了一个人(在另一端,他们将我发送为ClassB),但这个人是男性,返回false..为什么?
2个回答

1

您需要在PostPerson方法中添加[ServiceKnownType(typeof(Men))]属性。


0
正如Ryan Gross所提到的,您需要Men成为已知类型。这里是SO上类似的问题/答案。链接文章中未提及的一个选项是KnownType属性。以下是我过去使用过的代码示例。前提条件是该类是所有数据契约的基类,并且所有数据契约都在同一个程序集中:
/// <summary>
///   Base class for all data contracts.
/// </summary>
[DataContract(Name = "Base", Namespace = "your namespace")]
[KnownType("GetKnownTypes")]
public class BaseDC : IExtensibleDataObject
{
  #region Constants and Fields

  /// <summary>
  ///   Instance used to control access to the known types list.
  /// </summary>
  private static readonly object _knownTypesLock = new object();

  /// <summary>
  ///   Classes derived from this class.  Needed to ensure proper functioning of the WCF data
  ///   constract serializer.
  /// </summary>
  private static List<Type> _knownTypes;

  #endregion

  #region Properties

  /// <summary>
  ///   Gets or sets an <c>ExtensionDataObject</c> that contains data that is not recognized as belonging to the
  ///   data contract.
  /// </summary>
  public ExtensionDataObject ExtensionData { get; set; }

  #endregion

  #region Public Methods

  /// <summary>
  ///   Enumerates the types in the assembly containing <c>BaseDC</c> that derive from <c>BaseDC</c>.
  /// </summary>
  /// <returns>List of <c>BaseDC</c>-derived types.</returns>
  [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
    Justification = "Not appropriate for a property.")]
  public static IEnumerable<Type> GetKnownTypes()
  {
    lock (_knownTypesLock)
    {
      if (_knownTypes == null)
      {
        _knownTypes = new List<Type>();
        Assembly contractsAssembly = Assembly.GetAssembly(typeof(BaseDC));
        Type[] assemblyTypes = contractsAssembly.GetTypes();
        foreach (Type assemblyType in assemblyTypes)
        {
          if (assemblyType.IsClass && !assemblyType.IsGenericType)
          {
            if (assemblyType.IsSubclassOf(typeof(BaseDC)))
            {
              _knownTypes.Add(assemblyType);
            }
          }
        }

        _knownTypes.Add(typeof(BaseDC));
      }

      return _knownTypes;
    }
  }

  #endregion
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接