Custom Data Type for "HttpGet" Route in Asp.Net Web Api Project
<p>I try to add a variable of "custom data type" in my HttpGet Route.</p>

<p>I have this code:</p>

<pre><code>[HttpGet("{idObject}")]
public ResponseSchema Get(ObjectId idObject)
{
    if (idObject == null) {
        throw new BodyParseException();
    }

    var user = _usersLogic.GetById(idObject);

    if (user == null) {
        _response.Success = false;
        _response.ErrorCode = "UserDoesNotExist";
    }
    else {
        _response.Objects.Add(user);
    }

    return _response;
}
</code></pre>

<p>ObjectId is a Datatype defined in using MongoDB.Bson.</p>

<p>For the Json Serialization and Deserialization we already have the code to automatically convert on both sides. But can this be similarly done in the Url itself.</p>

<p>We are right now using this Mvc version:</p>

<pre><code>"Microsoft.AspNet.Mvc": "6.0.0-beta8"
</code></pre>

<p>So the URL looks like this:</p>

<pre><code>GET Users/55b795827572761a08d735ac
</code></pre>

<p>The code to parse it from "string" to "ObjectId" is:</p>

<pre><code> ObjectId.TryParse(idString, out idObject);
</code></pre>

<p>The question is where to put that TryParse code. Because I need to tell ASP.NET how it should parse the idObject from String to ObjectId. Since the URL basically is a string.</p>

<p>For Post or Put JSON Payload I already found a solution. I know that this is something different. But Probably it is helpful to understand the scenario, or find a solution to this scenario:</p>

<pre><code>public class EntityBaseDocument
{
    [JsonConverter(typeof(ObjectIdConverter))]
    public ObjectId Id { get; set; }
}

// Since we have this value converter. We can use ObjectId everywhere
public class ObjectIdConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value.ToString());
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        return new ObjectId(token.ToObject&lt;string&gt;());
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(ObjectId).IsAssignableFrom(objectType);
    }
}
</code></pre>