How to require parameters in action

拥有回忆 提交于 2019-12-11 05:58:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!