Path parameter mapping to DTO

Hello,

I have a situation where I need to use a class that handles encoding and decoding an identifier, in my application, using implicit operator. So when the Identity is used as an int it considered the decoded value, and string is the encoded value.

Below is the basic outline of the code:

public class Identity
{
	int? id;
	string encoded;

	public Identity(string encoded)
	{
		this.encoded = encoded;
	}

	public Identity(int id)
	{
		this.id = id;
	}

	public int GetId()
	{
		return id ?? 0; // decoding of encoded here
	}

	public string GetEncodedId()
	{
		return encoded ?? ""; // encoding of id here
	}

	public override string ToString()
	{
		return GetEncodedId();
	}

	public static implicit operator int(Identity d)
	{
		return d.GetId();
	}

	public static implicit operator string(Identity d)
	{
		return d.GetEncodedId();
	}

	public static implicit operator Identity(string encoded)
	{
		return new Identity(encoded);
	}

	public static implicit operator Identity(int id)
	{
		return new Identity(id);
	}
}

I use these serialize/deserialize functions:

JsConfig<Identity>.DeSerializeFn = (string encoded) => new Identity(encoded);
JsConfig<Identity>.SerializeFn = (Identity id) => id.ToString();

This is working great in my DTO:

[Route("/test")]
class TestRequest
{
    public Identity PersonId { get; set; }
}

JSON:

{ "personId": "encodedId" }

In my code, I use request.PersonId as the decoded Int. Everything works.

The problem is, I want to be able to use the Identity in the route, such as:

[Route("/test/{PersonId}")]
class TestRequest
{
    public Identity PersonId { get; set; }
}

But I can’t figure out how to map the string value to the Identity class. Some digging in the code, gets me to the StringMapTypeDeserializer. But Identity doesn’t have any public properties. How can I parse it, force the cast … (Identity)pathStringValue?

Any help would be greatly appreciated, it’s the last piece of the puzzle, as I say, it’s working great for DTOs, it’s just the Path that it’s not working on.

You can add into Identity class ParseJsv method. It will help to deserialize DTO when use it with [Route] attribute

public class Identity
{
....
        public static Identity ParseJsv(string encoded) => new Identity(encoded);
}
2 Likes

:smile: Thanks @xplicit You rock, that’s exactly what I needed.

I came so close earlier when I was messing around to get it to work, but I had used ParseJson … forgetting that the PathInfo used Jsv.