在ASP.NET Core 10 Web API中,WCF的 __type的等价物
我正在把我的项目从WCF迁移到ASP.NET Core 10。我确实有一个把基类作为输入的方法。在WCF中,成员名 __type 已经告诉服务它是什么类。
在ASP.NET Core中如何实现?
示例 - 服务端(服务器端):
class Fruit {}
class Apple : Fruit {}
class Orange : Fruit{}
[Route("SomeMethod")
SomeMethod(Fruit fruit) // takes base class as parameter
{
if (fruit is Apple) { /*got apple*/ }
else if (fruit is Orange) { /*got Orange*/ }
else { /*got new fruit*/ }
}
客户端:
var apple = new Apple();
service.SomeMethod(apple);
// this comes in WCF as Apple because __type == Apple
// In ASP.NET Core, it is passed as Fruit, so I need to write some mapping in ASP.NET Core
因此,服务器端的核心服务将通过调用 SomeMethod 来获取 Fruit。
解决方案
你可以使用 JsonPolymorphic,这是一个内置于.NET 7及以上版本的属性,能够让 System.Text.Json 在JSON反序列化时处理类继承。它的工作原理是在JSON载荷中嵌入一个判别字段,如 __type,以告诉反序列化器在载荷到达时应实例化哪个具体的子类。
[JsonPolymorphic(TypeDiscriminatorPropertyName = "__type")]
[JsonDerivedType(typeof(Apple), typeDiscriminator: "Apple")]
[JsonDerivedType(typeof(Orange), typeDiscriminator: "Orange")]
public class Fruit { }
public class Apple : Fruit
{
public string Variety { get; set; }
}
public class Orange : Fruit
{
public string Origin { get; set; }
}
[HttpPost]
[Route("SomeMethod")]
public IActionResult SomeMethod([FromBody] Fruit fruit)
{
if (fruit is Apple apple) { /* got Apple */ }
else if (fruit is Orange orange) { /* got Orange */ }
return Ok();
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。