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

本秂侑毒 提交于 2019-11-29 03:23:27

In addtion to the first answer you should be able to get your code working allow the omitting of the prefix's on the url if you move all the optional's to the end of the method declaration and I always set them to NULL for good measure:

FileDto fileDto,
bool linkFromExistingFile,
Guid? previousTrackingId = null,
int? existingFileId = null

But

Good point re: an empty URL value with a prefix... is it the same as a NULL... Thinking about strings, Is ?q= an empty string or a null??

I have attempted to find the exact logic in the framework (and continue to look) that raises these errors but during my experimentation I did find that specifying a binder directly on a URL parameter seems to bypass the logic and allow an empty value after a prefix without a model binding error.

Like so:

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get(
        [FromUri(BinderType = typeof(TypeConverterModelBinder))] string q = null,
        [FromUri(BinderType = typeof(TypeConverterModelBinder))] int? value = null)
    {
        if (!ModelState.IsValid)
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }

        return new string[] { value.HasValue ? value.Value.ToString() : "", q };
    }     
}

I solved this by moving all the parameters to a single class.

public class UploadFileModel {
   public FileDto FileDto { get; set; }
   public int? ExistingFileId { get; set; }
   public bool LinkFromExistingFile { get; set; }
   public Guid? PreviousTrackingId { get; set; }
}

public HttpResponseMessage UploadFile([FromUri]UploadFileModel model)
{
   // ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!