Sunday, December 4, 2022

ASP.NET Core: Suppress Implicit Required Model Validation For Non Nullable Reference Types

In this post, let's see how we can disable implicit required model validation for non-nullable reference types when the nullable context is enabled in an ASP.NET Core Web Application.

Let's consider the following sample.

#nullable enable
 
using Microsoft.AspNetCore.Mvc;
 
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
// Register Services.
builder.Services.AddControllers();
 
WebApplication app = builder.Build();
 
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
 
app.MapControllers();
 
app.Run();

[ApiController]
[Route("[controller]")]
public class EmployeesController : ControllerBase
{
    [HttpPost]
    public ActionResult<EmployeeCreate([FromBodyEmployee employee)
    {
        return employee;
    }
}
 
public class Employee
{
    public string FirstName { getset; }
 
    public string LastName { getset; }
 
    public Employee(string firstNamestring lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

Here if we try to post a payload with null values for reference types that are not marked with nullable, ASP.NET Core by default is doing a model validation and throwing an error.

For example, here if we post a payload without setting the value for LastName, I am getting the following error.
ASP.NET Core Model Validation
But there are times, we need to offload the validation to a separate module. In that case, we can easily suppress this validation as follows.
builder.Services.AddControllers(x =>
{
    x.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;
});
And then, we won't be seeing that validation anymore.
ASP.NET Core: Suppress Implicit Required Attribute For Non Nullable Reference Types
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment