Skip to content

Commit 9d35955

Browse files
author
youssefm
committed
Avoid logging model errors for invalid fields in value validation
1 parent bc62072 commit 9d35955

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/System.Web.Http/Validation/DefaultBodyModelValidator.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,13 @@ private bool ShallowValidate(ModelMetadata metadata, ValidationContext validatio
173173
{
174174
key = keyBuilder.AppendTo(key);
175175
}
176+
177+
// Avoid adding model errors if the model state already contains model errors for that key
178+
// We can't perform this check earlier because we compute the key string only when we detect an error
179+
if (!validationContext.ModelState.IsValidField(key))
180+
{
181+
return false;
182+
}
176183
}
177184
validationContext.ModelState.AddModelError(key, error.Message);
178185
isValid = false;

test/System.Web.Http.Test/Validation/DefaultBodyModelValidatorTest.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,25 @@ public void MultipleValidationErrorsOnSameMemberReported()
143143
ModelState streetState = actionContext.ModelState["Street"];
144144
Assert.Equal(2, streetState.Errors.Count);
145145
}
146+
147+
[Fact]
148+
public void ValidationErrorsNotAddedOnInvalidFields()
149+
{
150+
// Arrange
151+
ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
152+
HttpActionContext actionContext = ContextUtil.CreateActionContext();
153+
object model = new Address() { Street = "Microsoft Way" };
154+
155+
actionContext.ModelState.AddModelError("Street", "error");
156+
157+
// Act
158+
new DefaultBodyModelValidator().Validate(model, typeof(Address), metadataProvider, actionContext, string.Empty);
159+
160+
// Assert
161+
Assert.Contains("Street", actionContext.ModelState.Keys);
162+
ModelState streetState = actionContext.ModelState["Street"];
163+
Assert.Equal(1, streetState.Errors.Count);
164+
}
146165
}
147166

148167
public class Person

0 commit comments

Comments
 (0)