using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Text; using HealthMonitor.Util.Entities.Base; namespace HealthMonitor.WebApi.Controllers.Base { public class DefaultControllerBase : ControllerBase where T: EntityBase { /// /// 验证参数有效性 /// /// 可选,若提供则在参数有效性不通过时,会给参数赋默认值 protected void AssertModelStateIsValid(T? model = null) { if (!ModelState.IsValid) { var message = new StringBuilder(); var entityType = typeof(T); if (entityType.IsSubclassOf(typeof(HealthMonitorEntityBase))) message.Append("HealthMonitor"); //else if (entityType.IsSubclassOf(typeof(TelpoCommonEntityBase))) message.Append("TelpoCommon"); //else if (entityType.IsSubclassOf(typeof(GpsLocationHistoryEntityBase))) message.Append("GpsLocationHistory"); message.Append($" [{entityType.FullName}], Error Message: "); foreach (var kv in ModelState) { if (kv.Value.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid) { message.Append(string.Join(", ", kv.Value.Errors.Select(e => e.ErrorMessage))); } } if (model != null) model.AssertValidate(); else throw new ArgumentException(message.ToString()); } } } }