skip to Main Content

When I return a GUID from a controller action in ASP.NET, I get a string back:

public class MyController : ControllerBase
{
    // returns `"544b4406-9cb8-4c4f-8ea2-bc535b0d3888"`
    [HttpGet]
    public Guid Get() => Guid.NewGuid();
}

This works even for complex models:

public class MyModel {
    public Guid Id { get; set; } = Guid.NewGuid();
}

public class MyController : ControllerBase
{
    // returns `{ id: "544b4406-9cb8-4c4f-8ea2-bc535b0d3888" }`
    [HttpGet]
    public MyModel Get() => new MyModel();
}

How can I get a custom MyId class to be returned as string as well?

public class MyController : ControllerBase
{
    // returns `{}`
    [HttpGet]
    public MyId Get() => MyId.NewId();
}

2

Answers


  1. Chosen as BEST ANSWER

    The answer was: Use a custom JsonConverter:

    [JsonConverter(typeof(MyIdJsonConverter))]
    [ModelBinder(BinderType = typeof(MyIdModelBinder))]
    [SwaggerSchemaFilter(typeof(MyIdSchemaFilter))]
    public class MyId : IEquatable<MyId>, IEquatable<string> {
        private readonly string id;
    }
    
    public class MyIdJsonConverter : JsonConverter<MyId>
    {
        public override MyId? Read(
            ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options
        ) => // e.g. MyId.Parse(reader.GetString());
    
        public override void Write(
            Utf8JsonWriter writer,
            MyId value,
            JsonSerializerOptions options
        ) => // e.g. writer.WriteStringValue(value.ToString());
    }
    

  2. The problem is that the MyId does not have any public properties. Therefore, the serialization result is empty.
    You need to write your own JsonConverter for MyId type.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search