Home > database >  Disable null validation in ASP.Net 6 project
Disable null validation in ASP.Net 6 project

Time:03-04

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>

CodePudding user response:

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.

  • Related