/// <summary> /// <httpRuntime requestValidationType="xxx.CustomRequestValidator" /> /// </summary> public class CustomRequestValidator : RequestValidator { public readonly static object CustomRequestValidatorKey = new object(); protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex) { var obj = context.Items[CustomRequestValidatorKey]; if (obj != null) { var notValid = (RequestNotValidationSource)obj; if (notValid == RequestNotValidationSource.All) { validationFailureIndex = 0; return true; } RequestNotValidationSource tmp; if (Enum.TryParse(requestValidationSource.ToString(), out tmp) && notValid.HasFlag(tmp)) { validationFailureIndex = 0; return true; } } return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex); } } /// <summary> /// 重写验证逻辑 /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class CustomRequestValidatorAttribute : FilterAttribute, IAuthorizationFilter { /// <summary> /// 不验证哪些数据 /// </summary> public RequestNotValidationSource? NotValidationSource { get; set; } public CustomRequestValidatorAttribute() { NotValidationSource = null; } /// <summary> /// /// </summary> /// <param name="notValidationSource">不验证哪些数据</param> public CustomRequestValidatorAttribute(RequestNotValidationSource notValidationSource) { NotValidationSource = notValidationSource; } public virtual void OnAuthorization(AuthorizationContext filterContext) { filterContext.HttpContext.Items[CustomRequestValidator.CustomRequestValidatorKey] = NotValidationSource; } } /// <summary> /// 不验证哪些数据 /// </summary> [Flags] public enum RequestNotValidationSource { QueryString = 1, Form = 2, Cookies = 4, Files = 8, RawUrl = 16, Path = 32, PathInfo = 64, Headers = 128, All = 256 }
时间: 2025-01-06 03:27:34