ASP.NET Core 10 Web API 如何实现 WCF 的 __type 多态参数?
可以使用 System.Text.Json 的多态反序列化配置,在 Fruit 上注册允许的派生类型,并将类型判别字段设置为 __type。客户端发送对应的判别值后,服务端就能将 Fruit 参数反序列化为 Apple 或 Orange。
以下方案适用于使用默认 System.Text.Json JSON 格式化器的 ASP.NET Core 10 Web API。如果项目已经切换到 Newtonsoft.Json,则需要使用对应的配置方式。ASP.NET Core JSON 格式化器说明
为什么服务端只得到 Fruit?
HTTP 请求传输的是序列化后的数据。客户端执行 new Apple() 时,请求中不一定会自动携带服务端可识别的派生类型信息。
服务端按 Fruit 读取 JSON 时,需要知道哪个字段用于区分类型,以及每个字段值对应哪个派生类。仅有继承关系或派生类属性,不足以还原实际类型。System.Text.Json 多态反序列化说明
配置类型判别字段和服务端接口
下面是基于 Controller 的 Program.cs 示例:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
[JsonPolymorphic(TypeDiscriminatorPropertyName = "__type")]
[JsonDerivedType(typeof(Apple), "Apple")]
[JsonDerivedType(typeof(Orange), "Orange")]
public class Fruit { }
public class Apple : Fruit { }
public class Orange : Fruit { }
[ApiController]
public class FruitController : ControllerBase
{
[HttpPost("SomeMethod")]
public IActionResult SomeMethod([FromBody] Fruit fruit)
{
if (fruit is Apple)
{
return Ok(new { receivedType = "Apple" });
}
if (fruit is Orange)
{
return Ok(new { receivedType = "Orange" });
}
return Ok(new { receivedType = "Fruit" });
}
}
JsonDerivedType 建立了 "Apple" 到 Apple、"Orange" 到 Orange 的映射。TypeDiscriminatorPropertyName 将默认的 $type 字段改为 __type,无需再给 Fruit 添加同名属性。类型判别字段 API
客户端发送什么数据?
向 /SomeMethod 发送 POST 请求,设置 Content-Type: application/json,请求体如下:
{
"__type": "Apple"
}
按照上述配置,服务端会将这个请求反序列化为 Apple。发送 "__type": "Orange" 则会得到 Orange。接口参数绑定的是整个请求体,因此无需再包一层 fruit。
如果 .NET 客户端共享了带上述特性的模型,且 client 已配置 API 的 BaseAddress,可以显式按基类契约发送:
using System.Net.Http.Json;
using var response = await client.PostAsJsonAsync<Fruit>(
"SomeMethod",
new Apple());
response.EnsureSuccessStatusCode();
保留泛型参数 <Fruit>,让序列化器使用 Fruit 上的多态配置。如果泛型参数被推断为 Apple,则不能保证生成服务端需要的类型判别字段。多态序列化的声明类型要求
迁移时需要注意什么?
__type的值必须与注册的判别值一致。如果旧 WCF 请求中的实际值包含其他信息,应按真实请求调整映射,不能仅根据示例假定它一定是"Apple"。- 对于示例中可实例化的
Fruit,没有类型判别字段的{}会按基类读取。未注册的判别值默认会导致反序列化错误,不会自动进入方法里的else分支。 - 新增派生类时,需要补充对应的注册和客户端契约。现有的
else分支无法自动识别未来新增的任意类型。 - 默认应将
__type放在 JSON 对象开头。如果外部客户端无法保证顺序,可以考虑设置JsonSerializerOptions.AllowOutOfOrderMetadataProperties = true,但这可能增加大型请求的缓冲开销。元数据顺序说明
要完整兼容旧 WCF 客户端,还需要核对实际请求的字段值、JSON 结构和调用协议。
备注:内容仅供参考。
