.Net Core Web Api使用模型驗證驗證參數合法性

  • 在接口開發過程當中免不了要去驗證參數的合法性,模型驗證就是幫助咱們去驗證參數的合法性,咱們能夠在須要驗證的model屬性上加上Data Annotations特性後就會自動幫咱們在action前去驗證輸入數據的合法性。

1.定義一個Person類前端

public class PersonDto
{
public string Name { get; set; } public string Phone { get; set; } public int Age { get; set; } }

Person類有三個屬性,姓名,電話,年紀。ide

2.建立一個接口並以Person做爲input參數而且返回input對象post

public PersonDto Demo(PersonDto input)
{
    var str = string.Empty;
    PersonDto dto = new PersonDto
    {
      Name = input.Name,
      Age=input.Age,
      Phone=input.Phone,
     };
   return dto;
 }

3.用postman來調用這個接口  測試

    

     很明顯我傳入的參數是不合法的,可是接口依舊執行了。 那怎麼去驗證參數的合法性呢?在接口裏面寫if嗎?這時候模型驗證就發揮做用啦。 ui

4.修改以前的Person類,引入using System.ComponentModel.DataAnnotations;

public class PersonDto
    {
        [Required(ErrorMessage = "姓名不能爲空"), MaxLength(10, ErrorMessage = "名字太長啦"), MinLength(0, ErrorMessage = "名字過短")]
       [ RegularExpression(@"^[\u4e00-\u9fa5]+$", ErrorMessage = "姓名必須是中文")]
        public string Name { get; set; }

        [Required(ErrorMessage = "手機號碼不能爲空"), RegularExpression(@"^\+?\d{0,4}?[1][3-8]\d{9}$", ErrorMessage = "手機號碼格式錯誤")]
        public string Phone { get; set; }

        [Range(1, 1000, ErrorMessage = "年紀必須在0-99之間")]
        public int Age { get; set; }
    }

在次調用這個接口。spa

    

     若是參數參數的不合法會直接400且會根據定義的提示去提示前端參數哪裏不合法。可是不少小夥伴的返回值都是通用的,怎麼把這些提示放到本身的通用返回值裏面呢?code

5.定義一個通用的返回值

    public class ResponseDto
    {/// <summary>
        /// 詳細錯誤信息
        /// </summary>
        public string message { get; set; }

        /// <summary>
        /// 具體業務參數
        /// </summary>
        public object data { get; set; }
    }

6.定義一個CustomResultFilter

public class CustomResultFilter : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {

            if (!context.ModelState.IsValid)
            {
                ResponseDto result = new ResponseDto();

                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        result.message += error.ErrorMessage + ",";
                        result.data = "{}";
                    }
                }
                result.message = result.message.TrimEnd(',');
                context.Result = new JsonResult(result);
            }
            else
            {
                var result = context.Result as ObjectResult ?? null;
                context.Result = new OkObjectResult(new ResponseDto
                {
                    message = "成功",
                    data = result == null ? "{}" : result.Value
                });
                base.OnResultExecuting(context);

            }
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
        }

使用ModelState.IsValid來判斷模型驗證是否經過。對象

7.配置過濾器

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(CustomResultFilter));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Title = " API",
                    Version = "v1",
                    Description = "RESTful API",
                    TermsOfService = " Service",
                    Contact = new Contact { Name = "", Email = "", Url = "" }
                });
            });
        }

  8.測試

  

    模型驗證經過blog

  

相關文章
相關標籤/搜索