Disable null validation in ASP.Net 6 project

Viewed 2243

I have a really simple ASP.Net WebAPI project created in .Net 6. Given this controller method:

[HttpPost]
public async Task DoStuff(MyClass input)
{
   // snip
}

where MyClass looks like this:

public class MyClass
{
    public string MyData { get; set; }
}

Posting this to the DoStuff method used to be allowed in previous versions of ASP.Net:

{
    MyData: null
}

Now however, it gives a 400 response unless I declare MyData as a string? instead of a string. My problem is that the MyClass class can not be altered, so I can't update MyData to be of type string?. Is there a way to disable the automatic null validation that ASP.Net does on MyClass properties? Adding <Nullable>disable</Nullable> to the csproj file for the WebAPI project doesn't seem to do anything. My current csproj looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Platforms>x64</Platforms>
    <Nullable>disable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <NoWarn>1701;1702;1591</NoWarn>
    <UserSecretsId>MyProject</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\AnotherProject.csproj" />
  </ItemGroup>

</Project>
2 Answers

This is a feature of C# 8, nullable reference types and in .NET 6 they are enabled by default. To turn it off, in your csproj file add this line <Nullable>disable</Nullable>. For example:

<PropertyGroup>
  <Nullable>disable</Nullable>
</PropertyGroup>

Also, if MyClass is in another project, add <Nullable>disable</Nullable> there as well.

If you disable nullable in your csproj, it may cause warnings when you use the nullable operator(?). Adding the following code to your .editorconfig will allow you to use both methods (nullable or without nullable) without any additional warnings.

You can edit your .editorconfig file in your solution project. Added these lines at the end of section [*.{cs,vb}]

#### Naming styles ####
[*.{cs,vb}]

# CS8618: Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
dotnet_diagnostic.CS8618.severity = none

# CS8601: Possible null reference assignment.
dotnet_diagnostic.CS8601.severity = none 
Related