ASP.NET Core MVC 参数化验证,条件验证或根据其父类对属性进行验证。
创始人
2024-09-15 07:00:46
0

在ASP.NET Core MVC中,可以使用数据注解来进行参数化验证、条件验证或根据其父类对属性进行验证。下面是一个包含代码示例的解决方法:

首先,创建一个ViewModel类,该类用于接收传入的参数并进行验证。

using System.ComponentModel.DataAnnotations;

public class MyViewModel
{
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [Range(18, 99, ErrorMessage = "Age must be between 18 and 99")]
    public int Age { get; set; }

    [RequiredIf(nameof(Age), 30, ErrorMessage = "Email is required if age is 30")]
    public string Email { get; set; }
}

接下来,创建一个自定义的验证特性,用于实现条件验证。

using System;
using System.ComponentModel.DataAnnotations;

public class RequiredIfAttribute : ValidationAttribute
{
    private readonly string _propertyName;
    private readonly object _propertyValue;

    public RequiredIfAttribute(string propertyName, object propertyValue)
    {
        _propertyName = propertyName;
        _propertyValue = propertyValue;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_propertyName);

        if (property == null)
        {
            throw new ArgumentException($"Property {_propertyName} not found.");
        }

        var propertyValue = property.GetValue(validationContext.ObjectInstance);

        if (propertyValue.Equals(_propertyValue) && string.IsNullOrEmpty(value?.ToString()))
        {
            return new ValidationResult(ErrorMessage);
        }

        return ValidationResult.Success;
    }
}

最后,在Controller中使用ModelState.IsValid来进行验证,并返回验证结果。

[HttpPost]
public IActionResult MyAction(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // 验证通过,执行相应的操作
        return Ok();
    }

    // 验证失败,返回错误信息
    var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
    return BadRequest(errors);
}

以上代码示例中,通过使用数据注解和自定义的验证特性,实现了参数化验证、条件验证和根据其父类对属性进行验证的功能。在ViewModel类中,可以通过数据注解来定义属性的验证规则。自定义的验证特性RequiredIfAttribute可以根据指定的条件决定是否进行验证。在Controller的Action方法中,使用ModelState.IsValid来判断验证是否通过,并根据需要返回相应的结果。

相关内容

热门资讯

开挂辅助!雀友会潮汕麻将开挂辅... 开挂辅助!雀友会潮汕麻将开挂辅助,wepoker永久免费脚本(透视)开挂辅助软件(的确有挂);1、很...
辅助开挂!博弈麻友圈辅助,we... 辅助开挂!博弈麻友圈辅助,we poker游戏下(透视)开挂辅助插件(有挂教程);亲,有的,ai轻松...
开挂辅助!九九山城辅助,红龙p... 开挂辅助!九九山城辅助,红龙poker辅助(透视)开挂辅助插件(有挂规律);是一款可以让一直输的玩家...
辅助开挂!拼十app辅助,we... 辅助开挂!拼十app辅助,wepoker透视有吗(透视)开挂辅助工具(有挂分析);拼十app辅助软件...
辅助开挂!hhpoker有没有... 辅助开挂!hhpoker有没有作比,智星德州有脚本吗(透视)开挂辅助插件(有挂教程);1.hhpok...
辅助开挂!丽水都莱大菠萝辅助,... 辅助开挂!丽水都莱大菠萝辅助,wepoker永久免费脚本(透视)开挂辅助插件(有挂透明挂);丽水都莱...
辅助开挂!闽游互动辅助器,we... 辅助开挂!闽游互动辅助器,werplan辅助软件(透视)开挂辅助安装(发现有挂);1、让任何用户在无...
开挂辅助!微信小程序挂机辅助,... 开挂辅助!微信小程序挂机辅助,德普之星辅助工具如何设置(透视)开挂辅助插件(有挂攻略);超受欢迎的微...
辅助开挂!广西老友麻将有挂吗,... 辅助开挂!广西老友麻将有挂吗,wepoker俱乐部辅助器(透视)开挂辅助插件(有挂分析);小薇(透视...
辅助开挂!微信小程序挂后台,h... 辅助开挂!微信小程序挂后台,hhpoker脚本下载(透视)开挂辅助脚本(真的有挂);微信小程序挂后台...