c# - 是否可以使用数据注释来验证传递给 Controller ​​的 Action 方法的参数?

标签 c# asp.net-mvc data-annotations

我正在使用数据注释来验证我在 ASP.NET MVC 中的模型。这适用于具有复杂参数的操作方法,例如,

public class Params  
{  
    [Required] string Param1 {get; set;}   
    [StringLength(50)] string Param2 {get; set;}  
}


ActionResult MyAction(Params params)  
{  
   If(ModeState.IsValid)  
   {  
      // Do Something  
   }  
}

如果我想将单个字符串传递给操作方法(如下所示)怎么办?有没有一种方法可以使用数据注释,或者我是否必须将字符串包装到一个类中?

ActionResult MyAction(string param1, string param2)  
{  
   If(ModeState.IsValid)  
   {  
     // Do Something  
   }  
}  

最佳答案

创建您自己的模型...

public class Params  
{  
    [Required] string param1 {get; set;}   
    [StringLength(50)] string param2 {get; set;}  
}

并更改服务器端 Controller 的签名:

[HttpGet]
ActionResult MyAction([FromUri] Params params)  
{  
    If(ModeState.IsValid)  
    {  
        // Do Something  
    }  
}  

如果您的客户端代码已经工作,您不必更改它...请注意,您的模型的属性与您现在传递的参数相同(string param1,string param2)... 并且区分大小写...

编辑: 我的意思是你可以用这种方式调用你的 Controller :

http://localhost/api/values/?param1=xxxx&param2=yyyy

关于c# - 是否可以使用数据注释来验证传递给 Controller ​​的 Action 方法的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2717250/

相关文章:

asp.net-mvc-5 - 电子邮件地址属性验证

c# - 向继承类添加数据注释

c# - 当职责不属于该类时,使用多态性而不是条件

c# - ASP.NET Core Action 筛选器未被调用

asp.net-mvc - MVC 捆绑客户端缓存

c# - 如何将整数列表传递给 MVC 操作?

c# - 设置单元测试以使用 Unity 测试 Controller

c# - 裸偏类

c# - 如何为我的每个类创建 C# 配置文件?

C#,空数据源,但仍然是列表框中的一个项目