Home > Enterprise >  Action method gets ignored when non-nullable property exists in nullable reference type enabled
Action method gets ignored when non-nullable property exists in nullable reference type enabled

Time:06-26

If I activate either Version 0 or Version 1 and press Execute while leaving the Swagger-UI textboxes empty, I get the following error:

enter image description here

It seems to me, the body of Get never gets invoked. For other versions, the Get is called as expected. How can it happen?

public class Contact
{
    public string Name { get; set; }                    // Version 0
    public string Name { get; set; } = null!;           // Version 1
    // public string Name { get; set; } = String.Empty; // Version 2
    // public string? Name { get; set; }                // Version 3
    // public string? Name { get; set; } = String.Empty;// Version 4
    public int Age { get; set; }
}

[ApiController]
[Route("api/[controller]/[action]")]
public class ContactsController : ControllerBase
{
    [HttpGet]
    public ActionResult Get([FromQuery] Contact c)
    {
        // The code below will never be executed when Version 1 is activated, why?

        if (c.Name is null)
            return Ok("Name is null");

        if (c.Name == String.Empty)
            return Ok("Name is empty");

        return Ok("End reached");
    }
}

CodePudding user response:

The behaviour is different depending on nullability of the property, and the value we're setting it at construction.

This means that:

ASP.NET Core is able to recognize whether a property is marked nullable (string?) or non-nullable (string).

ASP.NET Core is able to call, or not call a controller method, depending on the input. So there is code that decides whether to call your method, or not.

ASP.NET Core is able to check the values of the properties before calling your controller method.

As you can see in the response in your image, there is a part of the response that says The Name field is required. This leads us also to:

ASP.NET Core is able to know the names of properties of Contact class, which is why the response specifically tells us that Name is required.

The common part of Version 0 and Version 1 is that the Name property

  • is non-nullable
  • has the value of null after new Contact()

The common part of Version 2 and Version 4 is that the Name property

  • has the value of string.Empty after new Contact()

The common part of Version 3 and Version 4 is that the Name property

  • is nullable

By analysis of the above behaviours, we can deduce that the validation code is rejecting the input when it sees null in a non-nullable property.

  • Related