.net core 統一參數校驗及異常處理


.net core 統一參數校驗及異常處理

相信大家都知道在前后端分離的開發模式中,異常處理和參數檢驗都是很重要的事情

那么如何做好處理呢?

首先我們來介紹一下如何做參數校驗:

參數檢驗那我們一定會想到實體類屬性,Required 需要引用命名空間System.ComponentModel.DataAnnotations

其實除了Required 還有很多具體大家可以參考

https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations?redirectedfrom=MSDN&view=netcore-3.1

我們這里已注冊為例

首先來定義我們實體類

    public class UserRegisterPostVm
    {

        [Required(ErrorMessage = "用戶Code不能為空")]
        public string Code { get; set; }

        [Required(ErrorMessage = "用戶名稱不能為空")]
        public string Name { get; set; }

        [Required(ErrorMessage = "用戶年齡不能為空")]
        [Range(1, 100, ErrorMessage = "年齡必須介於1~100之間")]
        public int? Age { get; set; }

        [Required(ErrorMessage = "用戶郵箱不能為空")]
        [EmailAddress(ErrorMessage = "請填寫正確的郵箱地址")]
        public string Email { get; set; }
    }

實體屬性也可以都好隔開看個人的習慣,

下面來編寫我們的統一參數處理,這里我們是已中間件的形式

.netcore中的中間件大家應該都了解過如果不清楚的話推薦大家去看看

園子里有很多相關文章,可以自行了解

代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ApiSource
{
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var result = context.ModelState.Keys
                        .SelectMany(key => context.ModelState[key].Errors.Select(x => new ValidationError(key, x.ErrorMessage)))
                        .ToList();
                context.Result = new ObjectResult(result);
            }
        }
    }
    public class ValidationError
    {
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string Field { get; }
        public string Message { get; }
        public ValidationError(string field, string message)
        {
            Field = field != string.Empty ? field : null;
            Message = message;
        }
    }
}

startup.cs

            services.AddMvc(options =>
            {
                options.Filters.Add<ValidateModelAttribute>();
            });
            
            // 關閉netcore自動處理參數校驗機制
            services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM