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<Employee> Create([FromBody] Employee employee) { return employee; } } public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public Employee(string firstName, string 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 |
builder.Services.AddControllers(x => { x.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true; });
Hope this helps.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment