“The value ‘NaN’ is not valid.”

So, we’re in the progress if migrating a big project from .NET 4.5 to .NET 5 (.NET Core). In this process we’ve stumbled upon a few problems that could be solved by changing frontend and apps, but that would break older versions of them. So…

EDIT: I’ve added a new post with another solution which probably is a better solution. Check it out.


One of the problems was when frontend or app provided the value NaN in a querystring parameter. In the old solution this was ignored by the WebApi and the standard value from the endpoint was taken. But when testing around in the migrated project, the request failed with the error “The value ‘NaN’ is not valid.”.

Request: /list?skip=NaN&take=1

        public IActionResult List(int skip = 0, int take = 20)
            // code



Our solution was to preprocess the incoming Url and remove all NaN. This was done in Startup.cs in the Configure-method.

app.Use(async (context, next) =>
                if (context.Request.QueryString.Value.Contains("=NaN"))
                    var qs = QueryHelpers.ParseQuery(context.Request.QueryString.Value);
                    context.Request.QueryString = QueryString.Create(qs.Where(x => x.Value != "NaN"));
                await next();

Heads up

If you have endpoints that have doubles/floats etc that can be NaN you could probably solve this with a custom Modelbinder instead.