Why does ModelState.IsValid fail for my ApiController method that has nullable parameters?

Viewed 4831

I have an ApiController method that accepts several parameters, like so:

    // POST api/files
    public HttpResponseMessage UploadFile
    (
        FileDto fileDto,
        int? existingFileId,
        bool linkFromExistingFile,
        Guid? previousTrackingId
    )
    {
        if (!ModelState.IsValid)
            return Request.CreateResponse(HttpStatusCode.BadRequest);

        ...
    }

When I POST to this I'm putting the FileDto object in the body of the request, and the other parameters on the query string.

I've already discovered that I cannot simply omit the nullable parameters - I need to put them on the query string with an empty value. So, my query looks like this when I don't want to specify a value for the nullable parameters:

http://myserver/api/files?existingFileId=&linkFromExistingFile=true&previousTrackingId=

This does match my controller method, and when the method is executed, the nullable parameters are indeed null (as you'd expect).

However, the call to ModelState.IsValid returns false, and when I examine the erorrs it's complaining about both the nullable parameters. (The other bits of the model have no errors). The message is:

A value is required but was not present in the request.

Why does it think that a value was required / not present? Surely (a) a value is not required for a nullable, and (b) a value was (sort of) present - in a null-ish sort of a way?

2 Answers
Related