C
C#3y ago
Arkobat

Deserialize wrapper object in route

Hello. Does anyone know if it is possible to map deserilize a custom wrapper object in a route? IDs in my system is strings, and we have therefore made an External class. The only point of this, is to improve code readability, to easy be able to view what is ids, and what is not. We have made a serilizer, that maps maps the class to a string in any JSON schemes. However, this serilizer does not seem to work, when we use the class in a route. Can we do it via a serilizer or some middleware, or do I have to take a string as input, and map it to ExternalId in my controller?
[HttpGet("{id}")]
public async Task<MyDTO> GetSomething([FromRoute] ExternalId id)
{
var result = await _service.GetSomething(id);
return result.ToDTO();
}
[HttpGet("{id}")]
public async Task<MyDTO> GetSomething([FromRoute] ExternalId id)
{
var result = await _service.GetSomething(id);
return result.ToDTO();
}
public class ExternalId
{
public string Id { get; set; }

public ExternalId() {}
public ExternalId(string id)
{
Id = id;
}
public class ExternalId
{
public string Id { get; set; }

public ExternalId() {}
public ExternalId(string id)
{
Id = id;
}
6 Replies
Angius
Angius3y ago
This should work, just maybe get rid of the constructor Serialization generally requires a default ctor to be present, the easiest way to do that is to... just not define any ctor at all
Arkobat
ArkobatOP3y ago
I do have a no args construtor, just removed it to keep the code simpel. However, the id is just a ExternalId, with the inner string being null
Arkobat
ArkobatOP3y ago
Angius
Angius3y ago
Try [HttpGet("{Id}")] Casing might matter
Arkobat
ArkobatOP3y ago
Ahh... I found the fix, thanks to you! The issue was not spacing, but that my parameter was also named id
[HttpGet("{id}")]
public async Task<MyDTO> GetSomething(ExternalId id)
[HttpGet("{id}")]
public async Task<MyDTO> GetSomething(ExternalId id)
To fix this, I have to rename my outer id to something else
[HttpGet("{id}")]
public async Task<MyDTO> GetSomething(ExternalId externalId)
[HttpGet("{id}")]
public async Task<MyDTO> GetSomething(ExternalId externalId)
Thanks for the help!
Angius
Angius3y ago
Ah, yeah, that makes sense Glad you got it sorted
Want results from more Discord servers?
Add your server