问题
I want to validate that a parameter is present in the action.
public string PorCarrera([Required] DateTime fechaDesde, [Required] DateTime fechaHasta, string carrera = null) {
return InformacionInscripcionesViewModel.GetTotalesInscripcionesPorCarrera(fechaDesde, fechaHasta, carrera);
}
I would expect the framework to throw a BadRequest
when calling the action without parameters but it is not happening.
All examples talk about modelState.IsValid
but I don't have any model that represents this data, because these are just queries to a DB.
回答1:
What you need to is make a model to represent your parameters. Something like this:
public class PorCarreraModel
{
[Required]
DateTime fechaDesde { get; set; }
[Required]
DateTime fechaHasta { get; set; }
string carrera { get; set; }
}
Then you can make your controller action like this:
public IActionResult PorCarrera(PorCarreraModel model) {
if(ModelState.IsValid == false)
{
return BadRequest(ModelState);
}
string totals = InformacionInscripcionesViewModel.GetTotalesInscripcionesPorCarrera(model.fechaDesde, model.fechaHasta, model.carrera);
return Content(totals);
}
来源:https://stackoverflow.com/questions/39536081/how-to-require-parameters-in-action