通過引用系統類庫System.ComponentModel.DataAnnotations,實現模型的數據校驗。
更多模型驗證屬性官方說明:https://docs.microsoft.com/zh-cn/dotnet/api/system.componentmodel.dataannotations?view=net-5.0
public class DemoModel { /// <summary> /// 主鍵 /// </summary> public string Id { get; set; } /// <summary> /// 姓名 /// </summary> [Required(ErrorMessage = "姓名不能為空")] [StringLength(50, ErrorMessage = "姓名限制50個字符")] public string Name { get; set; } /// <summary> /// 年齡 /// </summary> [Required(ErrorMessage = "年齡不能為空")] [Range(10, 80,ErrorMessage = "年齡字段限制范圍 {1} - {2}")] public string Age { get; set; } /// <summary> /// 性別 /// </summary> [Required(ErrorMessage = "性別不能為空")] public string Gender { get; set; } }
Demo控制器接口:
/// <summary> /// 保存Demo數據 /// </summary> [HttpPost] [Route("save"), MapToApiVersion("1.0")] public async Task<IActionResult> SaveDemo_V1_0([FromBody] DemoModel model) { var result = await _mediator.Send(new SaveDemoCommand(model)); result.apiVersion = HttpContext.GetRequestedApiVersion().ToString();//獲取API版本號 return Ok(result); }
postman調用請求:
此時發現返回的數據格式需要調整為自定義的統一格式,需要在Startup文件中做修改:
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //模型綁定 特性驗證,自定義返回格式 services.Configure<ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { //獲取驗證失敗的模型字段 var errors = actionContext.ModelState .Where(e => e.Value.Errors.Count > 0) .Select(e => e.Value.Errors.First().ErrorMessage) .ToList(); var strErrorMsg = string.Join("|", errors); //設置返回內容 var result = new CommandResult<string> { success = false, message = strErrorMsg }; return new BadRequestObjectResult(result); }; }); }
CommandResult類:
public class CommandResult<T> { public CommandResult(); public bool success { get; set; } public string message { get; set; } public string errCode { get; set; } public int resCode { get; set; } public string apiVersion { get; set; } public int timestamp { get; set; } public T data { get; set; } }
調整好消息返回格式后再次postman調用:
此時發現返回的消息已經變成自定義的格式,問題得到解決。
參考文章:https://blog.csdn.net/joe96/article/details/93539675