1. 程式人生 > 實用技巧 >ASP.NET Core WebAPI 模型驗證 驗證特性自定義返回

ASP.NET Core WebAPI 模型驗證 驗證特性自定義返回

通過引用系統類庫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