API data validation


Scenario:

Create a Sign on service to allow creation of users in our app. Add validation for max/min length for UserName mode

Solution:


  1. 1
    2
    3
    [MaxLength(100, ErrorMessage = "Invalidparam*maximum length of 100*userName")]
    [MinLength(10)]
    public string UserName { get; set; }


  2.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var errors = modelState.Where(ms => ms.Value.Errors != null && ms.Value.Errors.Count > 0)
                    .SelectMany(ms => ms.Value.Errors)
                    .Select(e =>
                    {
                        if (e.message.Contains("*"))
                        {
                            var details = e.message.Split('*');
                            return new Error
                            {
                                Code = details[0],
                                Description = details[1],
                                Parameter = details[2]
                            };
                        }
    
                        return new Error
                        { Code = "InvalidRequest", Details = e.message };
                    }).ToList();

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...