AspNet 3.1-与另一个属性冲突:ThrowInvalidOperationException_Serialize



我的错误是控制器无法映射值;我有这样的情况来解释如何复制错误:

public class FooA {
public string Property1 { set; get; }
public virtual string Property2 { set; get; }
}

public class FooB : FooA {
public new string Property2 { set; get; } 
public string Property3 { set; get; }
}

正如您所知,属性Property2对于两个类都是通用的,因此当您在任何控制器中使用此操作时:

public async task<string> ActionA([FromBody] FooA fooA)
{
return string.Empty;
}

// The error is thrown in this unwrapping.
public async task<string> ActionB([FromBody] FooB fooB)
{
return string.Empty;
}

FooA的有效载荷是请求的:

{
"Property1" : "abc",
"Property2" : "def"
}

FooB的有效载荷是请求的:

{
"Property2" : "abc",
"Property3" : "def"
}

将抛出此异常:

System.InvalidOperationException: The JSON property name for 'FooB' collides with another property.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(JsonClassInfo jsonClassInfo, JsonPropertyInfo jsonPropertyInfo)
at System.Text.Json.JsonClassInfo..ctor(Type type, JsonSerializerOptions options)

我已经添加了属性,如[JsonIgnore],但它失败了,负载与第一个负载类似。

或:

services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
});

但这是不可能的,我的想法是要坚定,避免改变整个解决方案。这意味着开放扩展(意味着扩展将解决未来的问题(对(已经实现的(更改关闭。

您在AddJsonOptions中是否有一个特定的设置,允许继承的冲突始终使用子类自动解决?

注意01:即使添加了virtual-ans-new reserver关键字,控制器也会抛出相同的异常。

你必须修复类,你有两个选择

常见的

public class FooA
{
public string Property1 { set; get; }
public virtual string Property2 { set; get; }
}
public class FooB : FooA
{
public override string Property2 { set; get; }
public string Property3 { set; get; }
}

或者如果你想访问2个属性

public class FooA
{
public string Property1 { set; get; }
public string Property2 { set; get; }
}
public class FooB : FooA
{
public new string Property2 { set; get; }
public string Property3 { set; get; }
}

测试

var json = @"{
""Property2"" : ""abc"",
""Property3"" : ""def""
}";
var jsonDeserialized=System.Text.Json.JsonSerializer.Deserialize<FooB>(json);

测试reslut(json格式(

{
"Property2": "abc",
"Property3": "def",
"Property1": null
}

但我建议您安装Newtonsoft.Json序列化程序只需在启动中配置即可

using Newtonsoft.Json.Serialization;
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());

或者如果你只使用控制器

services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());

相关内容

  • 没有找到相关文章

最新更新