无法使TypeNameHandling工作

时间:2014-12-18 07:13:34

标签: c# asp.net asp.net-mvc inheritance json.net

我有这两个类和一个动作方法

public class A
{
    public int AProp { get; set; }
}

public class B : A
{
    public int BProp { get; set; }
}

public void TestAction(A a)
{
    if (!(a is B)) 
    {
        throw new Exception("Should be B!");
    }
}

在我的Global.asax的Application_Start我有下面的行。

var setting = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
setting.TypeNameHandling = TypeNameHandling.All;

我发布的json数据如下所示。

{$type: 'MyNamespace.B, MyAssembly', AProp: 1, BProp: 2}

当调用action时,我希望a param的类型为MyNamespace.B,但它是MyNamespace.A,因此会抛出异常。

我在下面编写了代码并测试了$typeTypeNameHandling是否正常工作,它们有效。 objA的类型为MyNamespace.AobjB的类型为MyNamespace.B

var json = @"{$type: 'MyNamespace.B, MyAssembly', AProp: 1, BProp: 2}";

var objA = JsonConvert.DeserializeObject(json, typeof(A), new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.None
});

var objB = JsonConvert.DeserializeObject(json, typeof(A), new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
});

使用ASP.NET MVC控制器的Action参数处理继承的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

您似乎在ASP.NET Web API基础结构上设置了TypeNameHandling设置,而不是ASP.NET MVC。所以这适用于您的Web API控制器。

ASP.NET MVC的默认值提供程序工厂不使用Json.NET。它使用内置的JavaScriptSerializer。如果您希望它使用Json.NET,您可以检查实现自定义工厂的following answer

ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().Single());
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());