Search code examples
c#asp.net-web-api

How to get nullable non-primitive parameters working with ASP.NET Core 8 Web API


Given this controller code:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    public string Get([FromQuery]TestInput? testInput)
    {
        return "OK";
    }
}

public class TestInput
{
    public string Value { get; set; }
}

How do I make /test route work?

Currently I'm getting this:

{
    "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "errors": {
        "Value": [
            "The Value field is required."
        ]
    },
    "traceId": "00-a6893dc23be5689c4b2219faf6f0e705-5fa0968422975595-00"
}

Implying that ? wasn't honored.

Note: I can get it working by making string properties on my model nullable, but that's not what I want as it's a mess. I could possibly get some luck with QueryStringValueProvider as suggested in this post, but that seems like overkill given the caliber of the issue. I'd like to get as codeless as possible solution for this rather a simple problem.


Solution

  • I reproduced your issue and found a couple of things that worked, courtesy of this answer.

    It seems that properties that are reference types have implicit required attributes when they are not nullable, so either disable this implicity:

    services.AddControllers(o => o.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
    

    Or make the property nullable.

    public class TestInput
    {
        public string? Value { get; set; }
    }