【问题标题】:receive abstract type in WebAPI as input在 WebAPI 中接收抽象类型作为输入
【发布时间】:2016-11-21 08:45:34
【问题描述】:

我在控制器中插入了以下 WebAPI 操作(示例):

public MyAbstractClass Action1(MyAbstractClass input)
{
    return input;
}

类结构是这样的:

public class MyAbstractClass 
{
   public int ID {get;set;}
   public string Name {get;set;}
}

public class ConcreteClass1 : MyAbstractClass 
{
   public string Foo {get;set;}
}

public class ConcreteClass1 : MyAbstractClass 
{
   public string Bar {get;set;}
}

我想使用描述具体类之一的 JSON 调用 WebAPI Action1,但它总是返回 null。

我的格式化程序是这样设置的:

public static void Configure(MediaTypeFormatterCollection formatters)
{
    var jsonFormatter = formatters.JsonFormatter;
    var settings = jsonFormatter.SerializerSettings;

    settings.Formatting = Formatting.Indented;
    settings.TypeNameHandling = TypeNameHandling.Objects;
    settings.ContractResolver = new CamelCaseExceptDictionaryKeysResolver();
}

private class CamelCaseExceptDictionaryKeysResolver : CamelCasePropertyNamesContractResolver
{
    protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
    {
        JsonDictionaryContract contract = base.CreateDictionaryContract(objectType);

        contract.DictionaryKeyResolver = propertyName => propertyName;

        return contract;
    }
}

注意我有一个自定义解析器并且我设置了settings.TypeNameHandling = TypeNameHandling.Objects;

所以我发送一个带有如下 JSON 的 post 请求:

{
   "$type": "MyNameSpace.SubNameSpace.ConcreteClass1"
   "id":100,
   "name":"some name",
   "foo":"some value of foo..."
}

但接收到null 作为输出.. 意味着消毒器无法对具体类进行反序列化。

我在这里错过了什么?

【问题讨论】:

    标签: json asp.net-web-api asp.net-web-api2 jsonserializer


    【解决方案1】:

    找到问题了。

    发布对象时我已经设置了

    "$type": "MyNameSpace.SubNameSpace.ConcreteClass1"
    

    需要设置为:

    "$type": "MyNameSpace.SubNameSpace.ConcreteClass1, DLLName"
    

    必须添加... ,DLLName,所以它将是完全限定名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-27
      • 2010-11-18
      • 2016-02-01
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      相关资源
      最近更新 更多