A few weeks ago I blogged about an issue where my breakpoint inside an ASP.NET MVC controller was never hit. The problem was caused by the built-in ModelStateInvalidFilter.
What I didnāt share in that blog post is why the ModelState was invalid in the first place. Letās see how a small change in my csproj file caused thisā¦
This is the model I was using:
public class EmailMessage | |
{ | |
public string FromAddress {get;set;} | |
public string ToAddress {get;set;} | |
} |
And this was an example I tried to send through my API:
var message=new EmailMessage | |
{ | |
ToAddress="to@test" | |
}; |
Everything worked until I made one small change. I updated my csproj file to start using nullable reference types:
<Nullable>Enable</Nullable> |
Now when I executed the same code it failed?! One look at the ModelState errors explained it:
The FromAddress field is required.
By enabling nullable reference types it handled both the āToAddressā and āFromAddressā as required.
To fix it, I had to update the DTO and enable nullability:
public class EmailMessage | |
{ | |
public string? FromAddress {get;set;} | |
public string ToAddress {get;set;} | |
} |