控制器中的验证属性

本文关键字:属性 验证 控制器 | 更新日期: 2023-09-27 18:15:43

我编写自己的属性来验证ASP中的模型。NET MVC:

public class ValidateImage : RequiredAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        // validate object
    }
}

和我这样使用这些属性:

public class MyModel
{
    [ValidateImage]
    public HttpPostedFileBase file { get; set; }
}

现在,我想让它在控制器中工作我将这个属性添加到一个属性中,而不是model:

public ActionResult EmployeePhoto(string id, [ValidateImage] HttpPostedFileBase file)
{
    if(ModelState.IsValid)
    {
    }
}

但是我的属性永远不会被执行。我怎么能使验证工作在控制器不使用模型?

控制器中的验证属性

不支持。只需编写一个视图模型来包装动作的所有参数:

public ActionResult EmployeePhoto(EmployeePhotoViewModel model)
{
    if (ModelState.IsValid)
    {
    }
}

可能像这样:

public class EmployeePhotoViewModel 
{
    public string Id { get; set; }
    [ValidateImage]
    public HttpPostedFileBase File { get; set; }
}