Asp.net Web Api nested model validation - c#

I'm running in to a bit of a problem in asp.net web api's model binding and validation (via data annotations).
It seems like if i have a model with property such as
Dictionary<string, childObject> obj { get; set; }
the childObject's validations don't seem to trigger. The data is bound from json with Json.Net serializer.
Is there some workaround or fix to this? Or have I misunderstood something else related to this?
I can't help but wonder why this doesn't result in errors:
public class Child
{
[Required]
[StringLength(10)]
public string name;
[Required]
[StringLength(10)]
public string desc;
}
//elsewhere
Child foo = new Child();
foo.name = "hellowrodlasdasdaosdkasodasasdasdasd";
List<ValidationResult> results = new List<ValidationResult>();
Validator.TryValidateObject(foo, new ValidationContext(foo), results, true);
// results.length == 0 here.
Oh god. I had forgotten to declare properties instead of fields.

There are 2 ways you can setup validation of the Dictionary Values. If you don't care about getting all the errors but just the first one encountered you can use a custom validation attribute.
public class Foo
{
[Required]
public string RequiredProperty { get; set; }
[ValidateDictionary]
public Dictionary<string, Bar> BarInstance { get; set; }
}
public class Bar
{
[Required]
public string BarRequiredProperty { get; set; }
}
public class ValidateDictionaryAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!IsDictionary(value)) return ValidationResult.Success;
var results = new List<ValidationResult>();
var values = (IEnumerable)value.GetType().GetProperty("Values").GetValue(value, null);
values.OfType<object>().ToList().ForEach(item => Validator.TryValidateObject(item, new ValidationContext(item, null, validationContext.Items), results));
Validator.TryValidateObject(value, new ValidationContext(value, null, validationContext.Items), results);
return results.FirstOrDefault() ?? ValidationResult.Success;
}
protected bool IsDictionary(object value)
{
if (value == null) return false;
var valueType = value.GetType();
return valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof (Dictionary<,>);
}
}
The other way is to create your own Dictionary as an IValidatableObject and do the validation in that. This solution gives you the ability to return all the errors.
public class Foo
{
[Required]
public string RequiredProperty { get; set; }
public ValidatableDictionary<string, Bar> BarInstance { get; set; }
}
public class Bar
{
[Required]
public string BarRequiredProperty { get; set; }
}
public class ValidatableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
Values.ToList().ForEach(item => Validator.TryValidateObject(item, new ValidationContext(item, null, validationContext.Items), results));
return results;
}
}

Validation always passes on fields because attributes can only be applied to properties. You need to change the fields name and desc into properties using auto implemented getter and setters.
These should then look something like
public string name { get; set; }

Related

Customs validation attribute with multiple value for Blazor EditForm validations

I want to check if the combination of column A and column B is unique in my blazor app.
To check if column A is unique is quite simple using a ValidationAttribute
public class MyClass
{
[IsUnique(ErrorMessage = "The entered value exists.")]
public string Code {get; set;}
}
public class IsUniqueAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var service = (DbService)validationContext.GetService(typeof(DbService))
bool exists = service.IsUnique((String)value);
if(exists == false)
{
return ValidationResult.Success;
}
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}
However, I do not know how to do the same thing when there are multiple values involved.
Say that I want to check if Code + Name is unique in the database for the following MyClass2.
public class MyClass2
{
public string Code {get; set;}
public string Name {get;set;}
}
I have tried using custom parameters:
public class IsCodeNameCombinationUniqueAttribute : ValidationAttribute
{
public string Name{ get; set; }
public override bool IsValid(object value)
{
//Validate
}
}
public class MyClass2
{
[IsCodeNameCombinationUnique(ErrorMessage = "The combination of Code and Name exists.", Name = Name)]
public string Code {get; set;}
public string Name {get;set;}
}
But it seems that I can only pass constants into the Name parameter.
Is there any way to make a custom ValidationAttribute to achieve what I want to?
Or should I be using custom validators instead? ( https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#validator-components)
The thing you are trying can be achieved using "Class-Level" Validation.
This can be done by implementing "IValidatableObject" in your model class and provide your validation logic in "Validate" method which is provided by "IValidatableObject".
In your case,
public class MyClass2 : IValidatableObject
{
public string Code {get; set;}
public string Name {get;set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var service = (DbService)validationContext.GetService(typeof(DbService))
bool exists = service.IsUniqueCombination(this.Code,this.Name);
if(exists)
{
yield return new ValidationResult("The combination of Code and Name exists.");
}
}
}

How can I get field value via reflection if name is different with field name

I have a class
[BsonIgnoreExtraElements]
public class CustomerModel
{
public string BranchID { get; set; }
public string BranchName { get; set; }
public string ReceiverID { get; set; }
public string ReceiverName{ get; set; }
}
I am writing a filter activity which can validate any field with specific value configured in MongoDB
"Exclude":[{"SourceCol":"Receiver Mode ID","Values":{"Value":["G","8","J"]}}
and written the comparing logic as
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
public static bool CheckPropertyCompare(CustomerModel customer, Exclude item)
{
var propertyValue = GetPropValue(customer, item.SourceCol);
return item.Values.Value.ToList().Contains(propertyValue);
}
In this, the Receiver Mode ID from MongoDB is actually looking for ReceiverID and I am stuck as to how can I resolve this issue. The only option I can think of is Key-Value pair collection to fetch the field name. but would like to know if there is any options like Attributes which can ease this process.
TIA
I think you can achieve that with Attributes as you say.
You can create a custom attribute, like this:
internal class MongoDBFieldAttribute : Attribute
{
public string Field{ get; private set; }
public MongoDBFieldAttribute(string field)
{
this.Field= field;
}
}
Then in your class:
public class CustomerModel
{
...
[MongoDBField("ReceiverModeID")]
public string ReceiverID { get; set; }
}
I think it could be better without spaces, it could be a problem, maybe yo can use a Trim() or similar... or yoy can try [MongoDBField("Receiver Mode ID")], never tried.
Then you can create a method than can relation both, property name and attribute name, for example:
private Dictionary<string, string> getRelationPropertyAttribute(Type type)
{
var dicRelation = new Dictionary<string, string>();
var properties = type.GetProperties();
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes(inherit: false);
var customAttributes = attributes
.AsEnumerable()
.Where(a => a.GetType() == typeof(MongoDBFieldAttribute));
if (customAttributes.Count() <= 0)
continue;
foreach (var attribute in customAttributes)
{
if (attribute is MongoDBFieldAttribute attr)
dicRelation[attr.Field] = property.Name;
}
}
return dicRelation;
}
Finally, you can play with that dictionary and in your method you can do something like that:
public static bool CheckPropertyCompare(CustomerModel customer, Exclude item)
{
var dicRelation = getRelationPropertyAttribute(typeof(CustomerModel));
var propertyName = dicRelation[item.SourceCol];
var propertyValue = GetPropValue(customer, propertyName);
return item.Values.Value.ToList().Contains(propertyValue);
}
It´s an idea...
Hope it helps.

Apply data annotations validation to all properties of same primitive datatype in a viewmodel

I searched google and SO for my scenario but not able to find an answer. I want to create a regular expression data annotation validation in a viewmodel class properties which are of double type. Since I have around 20 properties of type double. So I want to create a custom regular expression validation and apply to all double type properties without explicitly specifying on each property like:
[RegularExpression(#"^[0-9]{1,6}(\.[0-9]{1,2})?$", ErrorMessage ="Invalid Input")]
public double Balance { get; set; }
I am expecting thing like this:
[ApplyRegExpToAllDoubleTypes]
public class MyModel
{
public double Balance { get; set; }
public double InstallmentsDue { get; set; }
}
That's an interesting question. Here is how it can be done:
Define a custom ValidationAttribute and apply it at the class level by setting AttributeTargets.Class. Inside the ValidationAttribute, use reflection to get the double properties, then validate the value of each property. If any of the validations fail, return a validation failed message.
[ApplyRegExpToAllDoubleTypes]
public class MyModel {
public double Balance { get; set; }
public double InstallmentsDue { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class ApplyRegExpToAllDoubleTypes : ValidationAttribute {
protected override ValidationResult IsValid(object currentObject, ValidationContext validationContext) {
if (currentObject == null) {
return new ValidationResult("Object can't be null");
}
var properties = validationContext.ObjectType.GetProperties().Where(x => x.PropertyType == typeof(double));
foreach (var property in properties) {
//Here I compare the double property value against '5'
//Replace the following with the custom regex check
if ((double)property.GetValue(currentObject) < 5) {
return new ValidationResult("All double properties must be greater than 5");
}
}
return ValidationResult.Success;
}
}

Custom validation - Required only when method is put

I have two API endpoints, post and put:
[HttpPost]
[Route("projects")]
public IHttpActionResult Create([FromBody] ProjectDTO projectDto)
{
if (ModelState.IsValid)
{
var project = MappingConfig.Map<ProjectDTO, Project>(projectDto);
_projectService.Create(project);
return Ok("Project successfully created.");
}
else
{
return BadRequest(ModelState);
}
}
[HttpPut]
[Route("projects")]
public IHttpActionResult Edit([FromBody] ProjectDTO projectDto)
{
if (ModelState.IsValid)
{
var project = _projectService.GetById(projectDto.ProjectId);
if (project == null)
return NotFound();
project = Mapper.Map(projectDto, project);
_projectService.Update(project);
return Ok("Project successfully edited.");
}
else
{
return BadRequest(ModelState);
}
}
DTO looks like this:
public class ProjectDTO
{
public int ProjectId { get; set; }
[Required(ErrorMessage = "Name field is required.")]
public string Name { get; set; }
[Required(ErrorMessage = "IsInternal field is required.")]
public bool IsInternal { get; set; }
}
I'm trying to validate field ProjectId. ProjectId field should be required only in HttpPut method when I'm editing my entity.
Is it possible to make custom validation RequiredIfPut or something like that where that field will be required only when editing, but not when creating?
Here is what you can do using custom validation attribute:
public class RequiredWhenPutAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (System.Web.HttpContext.Current.Request.HttpMethod == "PUT")
{
var obj = (ProjectDTO)validationContext.ObjectInstance;
if (obj.ProjectId == null)
{
return new ValidationResult("Project Id is Required");
}
}
else
{
return ValidationResult.Success;
}
}
}
public class ProjectDTO
{
[RequiredWhenPut]
public int? ProjectId { get; set; }
}
Update:
In response to your comment, in order to make the solution more general, you can add a ParentDto class from which other classes are inherited and the shared property needs to be in the ParentDto class, as the following:
public class RequiredWhenPutAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (HttpContext.Current.Request.HttpMethod == "PUT")
{
var obj = (ParentDto)validationContext.ObjectInstance;
if (obj.Id == null)
{
return new ValidationResult(ErrorMessage);
}
}
else
{
return ValidationResult.Success;
}
}
}
public class ParentDto
{
[RequiredWhenPut(ErrorMessage = "Id is required")]
public int? Id { get; set; }
}
public class UserDTO : ParentDto
{
// properties
}
public class ProjectTypeDTO : ParentDto
{
// properties
}
public class ProjectDTO : ParentDto
{
// properties
}
That's one of the reasons, why I use different classes for both case (e.g. ProjectUpdateRequestDto and ProjectCreateRequestDto). Maybe both can be derived from a common base class, but even if not it makes it a lot easier to distinguish between both scenarios.
Also security could be a problem, cause if you use the same class it could be possible that the create requests already contains an id and if your create method simply maps the DTO to an database entity you could overwrite existing data. This means you have to be careful and think about such scenarios. If your create DTO class doesn't have that property it can't be set from the mapper and can't be malused.

DataAnnotations "NotRequired" attribute

I've a model kind of complicated.
I have my UserViewModel which has several properties and two of them are HomePhone and WorkPhone. Both of type PhoneViewModel. In PhoneViewModel I have CountryCode, AreaCode and Number all strings. I want to make the CountryCode optional but AreaCode and Number mandatory.
This works great. My problem is that in the UserViewModel WorkPhone is mandatory, and HomePhone is not.
Is there anyway I can dissable Require attributs in PhoneViewModel by setting any attributes in HomeWork property?
I've tried this:
[ValidateInput(false)]
but it is only for classes and methods.
Code:
public class UserViewModel
{
[Required]
public string Name { get; set; }
public PhoneViewModel HomePhone { get; set; }
[Required]
public PhoneViewModel WorkPhone { get; set; }
}
public class PhoneViewModel
{
public string CountryCode { get; set; }
public string AreaCode { get; set; }
[Required]
public string Number { get; set; }
}
[UPDATED on 5/24/2012 to make the idea more clear]
I'm not sure this is the right approach but I think you can extend the concept and can create a more generic / reusable approach.
In ASP.NET MVC the validation happens at the binding stage. When you are posting a form to the server the DefaultModelBinder is the one that creates model instances from the request information and add the validation errors to the ModelStateDictionary.
In your case, as long as the binding happens with the HomePhone the validations will fire up and I think we can't do much about this by creating custom validation attributes or similar kind.
All I'm thinking is not to create model instance at all for HomePhone property when there are no values available in the form (the areacode, countrycode and number or empty), when we control the binding we control the validation, for that, we have to create a custom model binder.
In the custom model binder we are checking if the property is HomePhone and if the form contains any values for it's properties and if not we don't bind the property and the validations won't happen for HomePhone. Simply, the value of HomePhone will be null in the UserViewModel.
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "HomePhone")
{
var form = controllerContext.HttpContext.Request.Form;
var countryCode = form["HomePhone.CountryCode"];
var areaCode = form["HomePhone.AreaCode"];
var number = form["HomePhone.Number"];
if (string.IsNullOrEmpty(countryCode) && string.IsNullOrEmpty(areaCode) && string.IsNullOrEmpty(number))
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
Finally you have to register the custom model binder in global.asax.cs.
ModelBinders.Binders.Add(typeof(UserViewModel), new CustomModelBinder());
So now of you have an action that takes UserViewModel as parameter,
[HttpPost]
public Action Post(UserViewModel userViewModel)
{
}
Our custom model binder come into play and of form doesn't post any values for the areacode, countrycode and number for HomePhone, there won't be any validation errors and the userViewModel.HomePhone is null. If the form posts atleast any one of the value for those properties then the validation will happen for HomePhone as expected.
I've been using this amazing nuget that does dynamic annotations: ExpressiveAnnotations
It allows you to do things that weren't possible before such as
[AssertThat("ReturnDate >= Today()")]
public DateTime? ReturnDate { get; set; }
or even
public bool GoAbroad { get; set; }
[RequiredIf("GoAbroad == true")]
public string PassportNumber { get; set; }
Update: Compile annotations in a unit test to ensure no errors exist
As mentioned by #diego this might be intimidating to write code in a string, but the following is what I use to Unit Test all validations looking for compilation errors.
namespace UnitTest
{
public static class ExpressiveAnnotationTestHelpers
{
public static IEnumerable<ExpressiveAttribute> CompileExpressiveAttributes(this Type type)
{
var properties = type.GetProperties()
.Where(p => Attribute.IsDefined(p, typeof(ExpressiveAttribute)));
var attributes = new List<ExpressiveAttribute>();
foreach (var prop in properties)
{
var attribs = prop.GetCustomAttributes<ExpressiveAttribute>().ToList();
attribs.ForEach(x => x.Compile(prop.DeclaringType));
attributes.AddRange(attribs);
}
return attributes;
}
}
[TestClass]
public class ExpressiveAnnotationTests
{
[TestMethod]
public void CompileAnnotationsTest()
{
// ... or for all assemblies within current domain:
var compiled = Assembly.Load("NamespaceOfEntitiesWithExpressiveAnnotations").GetTypes()
.SelectMany(t => t.CompileExpressiveAttributes()).ToList();
Console.WriteLine($"Total entities using Expressive Annotations: {compiled.Count}");
foreach (var compileItem in compiled)
{
Console.WriteLine($"Expression: {compileItem.Expression}");
}
Assert.IsTrue(compiled.Count > 0);
}
}
}
I wouldn't go with the modelBinder; I'd use a custom ValidationAttribute:
public class UserViewModel
{
[Required]
public string Name { get; set; }
public HomePhoneViewModel HomePhone { get; set; }
public WorkPhoneViewModel WorkPhone { get; set; }
}
public class HomePhoneViewModel : PhoneViewModel
{
}
public class WorkPhoneViewModel : PhoneViewModel
{
}
public class PhoneViewModel
{
public string CountryCode { get; set; }
public string AreaCode { get; set; }
[CustomRequiredPhone]
public string Number { get; set; }
}
And then:
[AttributeUsage(AttributeTargets.Property]
public class CustomRequiredPhone : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = null;
// Check if Model is WorkphoneViewModel, if so, activate validation
if (validationContext.ObjectInstance.GetType() == typeof(WorkPhoneViewModel)
&& string.IsNullOrWhiteSpace((string)value) == true)
{
this.ErrorMessage = "Phone is required";
validationResult = new ValidationResult(this.ErrorMessage);
}
else
{
validationResult = ValidationResult.Success;
}
return validationResult;
}
}
If it is not clear, I'll provide an explanation but I think it's pretty self-explanatory.
Just some observation: the following code couse a problem if the binding is more than simple filed. I you have a case that in object have nested object it going to skip it and caouse that some filed not been binded in nested object.
Possible solution is
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (!propertyDescriptor.Attributes.OfType<RequiredAttribute>().Any())
{
var form = controllerContext.HttpContext.Request.Form;
if (form.AllKeys.Where(k => k.StartsWith(string.Format(propertyDescriptor.Name, "."))).Count() > 0)
{
if (form.AllKeys.Where(k => k.StartsWith(string.Format(propertyDescriptor.Name, "."))).All(
k => string.IsNullOrWhiteSpace(form[k])))
return;
}
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
much thanks to Altaf Khatri

Categories