asp.net-coreroutesoptional-parameters

Confusion with Optional Parameters in ASP.NET Core Routing


I’m working with ASP.NET Core routing and have encountered some confusion with optional parameters. I have a route with an optional parameter id:

app.Map("products/details/{id?}", async context =>
{
    if (context.Request.RouteValues.ContainsKey("id"))
    {
        string? idValue = context.Request.RouteValues["id"] as string;
        bool isInt = long.TryParse(idValue, out long id);
        if (isInt)
        {
            await context.Response.WriteAsync($"Products details - {id}");
        }
        else
        {
            await context.Response.WriteAsync($"Needs to be a number");
        }
    }
    else
    {
        await context.Response.WriteAsync($"Products details - id is not supplied.");
    }
});

Issue:

I expected that if the id parameter is not supplied, it would be null but still have the key "id" in RouteValues. However, my if condition if (context.Request.RouteValues.ContainsKey("id")) evaluates to false when the id is not supplied, leading to the else block being executed.

Question:

How does the optional parameter work in this context? Why does context.Request.RouteValues.ContainsKey("id") return false when the id is null? shouldn't it contains the id key if it's null?


Solution

  • How does the optional parameter work in this context

    When a request URL matches a route that includes an optional parameter, and that parameter is not supplied in the URL, the parameter will not be added to the RouteValues dictionary.See this link. If you set default value for id, this might help solve your concerns.

    var tempId = "";
    if (context.Request.RouteValues.TryGetValue("id", out var id))
    {
        tempId = id as string;
    }
    else
    {
        tempId = "null";
    }