如何要求参数有效 [英] How to require parameters in action

查看:64
本文介绍了如何要求参数有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要验证操作中是否存在参数.

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);
        }

我希望框架在调用不带参数的动作时抛出BadRequest,但不会发生.

I would expect the framework to throw a BadRequest when calling the action without parameters but it is not happening.

所有示例都谈论modelState.IsValid,但是我没有任何代表该数据的模型,因为这些只是对数据库的查询.

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.

推荐答案

您需要做的是创建一个模型来表示您的参数.像这样:

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);
}

这篇关于如何要求参数有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆