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
The answer was: Use a custom
JsonConverter
: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
forMyId
type.