Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does ModelState.IsValid fail for my ApiController method that has nullable parameters?
    primarykey
    data
    text
    <p>I have an ApiController method that accepts several parameters, like so:</p> <pre><code> // POST api/files public HttpResponseMessage UploadFile ( FileDto fileDto, int? existingFileId, bool linkFromExistingFile, Guid? previousTrackingId ) { if (!ModelState.IsValid) return Request.CreateResponse(HttpStatusCode.BadRequest); ... } </code></pre> <p>When I POST to this I'm putting the <code>FileDto</code> object in the body of the request, and the other parameters on the query string.</p> <p>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:</p> <pre><code>http://myserver/api/files?existingFileId=&amp;linkFromExistingFile=true&amp;previousTrackingId= </code></pre> <p>This does match my controller method, and when the method is executed, the nullable parameters are indeed <code>null</code> (as you'd expect).</p> <p><strong>However</strong>, the call to <code>ModelState.IsValid</code> returns <code>false</code>, 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:</p> <blockquote> <p>A value is required but was not present in the request.</p> </blockquote> <p>Why does it think that a value was required / not present? Surely (a) a value is <em>not</em> required for a nullable, and (b) a value was (sort of) present - in a null-ish sort of a way?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload