代码改变世界

.net core入参验证 ---ValidationAttribute

2020-08-01 17:50  石吴玉  阅读(1776)  评论(0编辑  收藏  举报

思路:使用自定义特性方法,继承ValidationAttribute,为入参Model添加特性

using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.CodeAnalysis;
using Nebula.Sites.AuditLog.Controllers;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Nebula.Sites.AuditLog.Dto
{
  [AuditLogValidation]
  public class AuditLogDto
  {/// <summary>
    /// 原数据记录ID
    /// </summary>
    public string RecordID { get; set; }/// <summary>
    /// 操作类型:Insert,Delete,Update
    /// </summary>
    public string OperateType { get; set; }

    /// <summary>
    /// 操作人
    /// </summary>
    public string Operater { get; set; }    
  }

  /// <summary>
  /// 参数验证
  /// </summary>
  public class AuditLogValidationAttribute : ValidationAttribute
  {
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      var LogRequest = (AuditLogDto)value;string OperateType = LogRequest.OperateType.ToUpper();
      if (OperateType != "INSERT" && OperateType != "DELETE" && OperateType != "UPDATE")
      {
        throw new Exception( "OperateType Parameter error" );
      }return new ValidationResult( "Verified" );
    }
  }
}

由此,调用端无需做任何操作(且支持List<Model>)

        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="LogRequest"></param>
        [HttpPost]
        public void WriteLogs([FromBody] List<AuditLogDto> LogRequest)
        {
            //多组数据,必须全部验证通过才入库
            foreach (var log in LogRequest)
            {
                GetLogDB(log);
            }
        }

        /// <summary>
        /// 单条操作
        /// </summary>
        /// <param name="LogRequest"></param>
        [HttpPost]
        public void WriteLog([FromBody] AuditLogDto LogRequest)
        {
            //入库
            GetLogDB(LogRequest);
        }