Now, let’s go ahead and add a new validator with our rule directly in the WeatherForecast class: The FluentValidation.AspNetCore package installs both FluentValidation and also some extra functionality specific to ASP.NET Core that we’ll make use of a bit later. PM> install-package FluentValidation.AspNetCore
To add our simple validator, we first need to install FluentValidation in the package manager console: Adding a Simple FluentValidation Validator To put some rules around this, in the next section let’s add a simple validator to ensure that the value of TemperatureC cannot exceed 100. This is hotter than the temperature of the Sun, so we probably shouldn’t allow this into our system for a weather forecast! Notice however we’ve passed a value of 6000 as the value for TemperatureC.
So we now have the ability to add new weather forecast. This method accepts a WeatherForecast parameter from the body of an HTTP POST request, and returns the string “Success!”. Public ActionResult Post( WeatherForecast forecast) Now let’s add a method to the WeatherForecastController class: Return Enumerable.Range(1, 5).Select(index => new WeatherForecast We can see there’s a single method called Get() which returns some weather forecasts (an array of WeatherForecast ), which is the API called when we ran the application previously: To demonstrate the use of validation, we’re going to add a new API method that allows us to add a new forecast.įirst, let’s open up WeatherForecastController.cs. Now let’s hit CTRL-F5 to run our API and we should see some weather readings for the next few days: Let’s go ahead and create a File -> New -> ASP.NET Core 3.1 API using Visual Studio, accepting all the defaults.Īt the end of the wizard, we’ll end up with the familiar “Weather Forecast” API structure: