0

I am writing a web service (c#, minimal api) for a front end application in Typescript. For type checking I want to include a type property in my JSON returned from the web service.

Example:

Following result expected in the front end

{
   "name": "Jason",
   "type": "User"
}

The user class in the backend will look like this

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. Is there a way to tell the JSON serializer to do it for me?

var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<JsonOptions>(options =>
{
    //do something here to achieve a "type" property?
});
devil_inside
  • 412
  • 3
  • 9

1 Answers1

1

Minimal api uses built in System.Text.Json json serializer implementation which doesn't support polymorphic de\serialization of object.

To achieve that you want (not providing type explicitly) you'll have to use 3rd party json serializer such as Json.Net

Minimal api is highly opinionated by design and enabling Json.Net there is cumbersome.

Check out this answer for further info.

Monsieur Merso
  • 1,459
  • 1
  • 15
  • 18