How to Use Configuration with ValidateDataAnnotations

后端 未结 2 458
悲&欢浪女
悲&欢浪女 2021-01-21 05:01

I\'ve read the Microsoft documentation of fundamentals for Options and Configuration, but still can\'t find the right way to extract configuration into an object while validatin

2条回答
  •  囚心锁ツ
    2021-01-21 05:41

    There is still no answer as to how ValidateDataAnnotations work, but based on Nkosi's answer, I wrote this class extension to easily run the validation on-demand. Because it's an extension on Object, I put it into a sub-namespace to only enable it when needed.

    namespace Websites.Business.Validation {
        /// 
        /// Provides methods to validate objects based on DataAnnotations.
        /// 
        public static class ValidationExtensions {
            /// 
            /// Validates an object based on its DataAnnotations and throws an exception if the object is not valid.
            /// 
            /// The object to validate.
            public static T ValidateAndThrow(this T obj) {
                Validator.ValidateObject(obj, new ValidationContext(obj), true);
                return obj;
            }
    
            /// 
            /// Validates an object based on its DataAnnotations and returns a list of validation errors.
            /// 
            /// The object to validate.
            /// A list of validation errors.
            public static ICollection Validate(this T obj) {
                var Results = new List();
                var Context = new ValidationContext(obj);
                if (!Validator.TryValidateObject(obj, Context, Results, true))
                    return Results;
                return null;
            }
        }
    }
    

    Then in Startup it's quite straightforward

    EmailConfig EmailSection = Configuration.GetSection("Email").Get().ValidateAndThrow();
    services.AddSingleton(EmailSection);
    

    Works like a charm; actually works like I'd expect ValidateDataAnnotations to work.

提交回复
热议问题