ASP.NET WEB API 自訂模型校正過濾器

來源:互聯網
上載者:User

標籤:customers   build   修改   pre   uil   缺點   webapi   date   hone   

  對外公開WEB介面時,對模型校正是常見的安全常識,常見的寫法是在controller中判斷ModelState.IsValid,以註冊使用者API為例。

Model:

public class RegisterCustomerModel{        [Required(ErrorMessage = "姓名不可為空")]        [StringLength(10,ErrorMessage = "姓名長度不能超過10個字")]        public string Name { get; set; }        [Required(ErrorMessage = "電話不可為空")]        [RegularExpression(@"^1[34578]\d{9}$", ErrorMessage = "電話號碼格式不正確")]        public string Phone { get; set; }        [Required(ErrorMessage = "密碼不可為空")]        [StringLength(48, ErrorMessage = "密碼長度不能超過48個字元")]        public string Password { get; set; }}

 

列印校正失敗的錯誤訊息代碼:

public static class ModelStateExtension   {        public static string ToErrorMessage(this ModelStateDictionary modelStateDictionary)        {            var stringBuilder = new StringBuilder();            foreach (var value in modelStateDictionary.Values)            {                foreach (var error in value.Errors)                {                    stringBuilder.AppendLine(error.ErrorMessage);                }            }            return stringBuilder.ToString();        }   }

 Controller:

public ResponseProtocol Register(RegisterCustomerModel registerCustomerModel)  {            if (!ModelState.IsValid)            {                return new ResponseProtocol((int)ResponseResultEnum.ValidateError, ModelState.ToErrorMessage(), string.Empty);            }            Customer customer = new Customer            {                Name = registerCustomerModel.Name,                Phone = registerCustomerModel.Phone,                WeiXinNo = registerCustomerModel.WeiXinNo,                Company = registerCustomerModel.Company,                UpdateTime = DateTime.Now            };            _customerService.Add(customer);            return new ResponseProtocol((int)ResponseResultEnum.Success, "註冊成功", string.Empty);    }

  以上寫法是在controller裡進行校正,缺點是每個需要進行校正的controller都要寫一次,為了消除重複,可以將校正代碼寫入全域過濾器中,由過濾器進行統一模型校正,修改後的代碼:

public class ValidationModelFilter : ActionFilterAttribute    {        public override void OnActionExecuting(HttpActionContext actionContext)        {            //get方法不進行模型校正            if (actionContext.Request.Method.Method=="GET")            {                return;            }            if (!actionContext.ModelState.IsValid)            {                var error = JsonConvert.SerializeObject(new ResponseProtocol()                {                    Code =(int)ResponseResultEnum.ValidateError,                    Message = actionContext.ModelState.ToErrorMessage(),                    Data = string.Empty                });                var httpResponseMessage = new HttpResponseMessage                {                    Content = new StringContent(error)                };                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");                actionContext.Response = httpResponseMessage;            }        }    }

  然後在全域過濾器(WebApiConfig)註冊一下: config.Filters.Add(new ValidationModelFilter());

ASP.NET WEB API 自訂模型校正過濾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.