標籤: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 自訂模型校正過濾器