[英]Is there a dynamic way of including class name as property in JSON return value from web service
I am writing a web service (c#, minimal api) for a front end application in Typescript.我正在为 Typescript 中的前端应用程序编写 web 服务(c#,最小 api)。 For type checking I want to include a type property in my JSON returned from the web service.
对于类型检查,我想在从 web 服务返回的 JSON 中包含一个类型属性。
Example:例子:
Following result expected in the front end以下是前端预期的结果
{
"name": "Jason",
"type": "User"
}
The user class in the backend will look like this后端的用户 class 将如下所示
public class User {
public string Name { get; set; }
//I do not want to have this property in every class
public string Type {
get {
return "User";
}
}
}
This works fine, but I have to add the property Type to every single class in the web service.这工作正常,但我必须将属性 Type 添加到 web 服务中的每个 class 。 Is there a way to tell the JSON serializer to do it for me?
有没有办法告诉 JSON 串行器为我做这件事?
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<JsonOptions>(options =>
{
//do something here to achieve a "type" property?
});
Minimal api uses built in System.Text.Json json serializer implementation which doesn't support polymorphic de\serialization of object.最小的 api 使用内置System.Text.Json json 序列化程序实现,它不支持 ZA8CFDE861AC 的多态反序列化\CBD54B66.9FDE86311
To achieve that you want (not providing type explicitly) you'll have to use 3rd party json serializer such as Json.Net为了实现您想要的(不明确提供类型),您必须使用第 3 方 json 序列化程序,例如Json.Net
Minimal api is highly opinionated by design and enabling Json.Net there is cumbersome.最小的 api 在设计上是高度自以为是的,启用 Json.Net 很麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.