Search code examples
c#asp.net-coreminimal-apisasp.net-minimal-apis

Minimal API endpoint not allowing null for nullable int?


I have set up a .NET 8 Minimal API with an endpoint that accepts two query parameters, one is an int? and one is a string?.

Route.MapGet("/SearchForServiceCompany", 
             (IMapper _mapper, int? ServcoNo, string? Name) =>
{
    // code
} 

When I try to call the API from the frontend, if I don't pass a value for ServcoNo, I get a 400 bad request:

https://localhost:7094/ServiceCompany/SearchForServiceCompany?ServcoNo=&Name=%25Ohio%25

If I completely remove ServcoNo from the query string, it works fine, so it's not an issue with it being null, it's an issue with the query string being included while it is null. I would rather not have to add logic to determine if the query string is needed since this should be working.

Edit: I should also mention that the same is not true for string? Name. If i leave the query string but do not give it a value it works as expected


Solution

  • It looks like a bug to me. For now you can workaround by accepting string:

    Route.MapGet("/SearchForServiceCompany",
        (string? Name, string? ServcoNo = null) =>
        {
            var actualServcoNo = ServcoNo == null
                ? (int?)null
                : int.TryParse(ServcoNo, out var actual)
                    ? actual
                    : throw new BadHttpRequestException("...");
    

    Or by creating appropriate wrapper.

    There is a similar issue @github (for a bit different case but underlying handling could be the same), but I will open another one later to target this specific one.