Просто интересно, есть ли способ, позволяющий веб-API ASP.NET автоматически не возвращать неверный ответ на запрос при попытке вызвать действие контроллера, имеющее модель со свойством, не допускающим значения NULL, которому присвоено значение NULL.
p>
Возьмем следующую модель:
Код: Выделить всё
public record TestModel
{
public string Name { get; set; } = "";
}
Код: Выделить всё
RuleFor(model => model.Name)
.NotEmpty()
.WithErrorCode(ErrorConstants.NameCannotBeEmpty);
Код: Выделить всё
var result = await _postValidator.ValidateAsync(request);
if (!result.IsValid)
{
return GetValidationErrorResponse(result);
}
We then have a set of tests we run, where we want to explicitly test for either "Name": "" or "Name": null.
When we call the test with "Name": "" the controller POST action is called, and the manual test of the fluent validator is called, which results in the BadRequest response containing the correct error code.
When we call the test "Name": null the controller POST action is not called, and it just returns the standard ASPNET BadRequest object, which states the name of the field but as it's not hitting the fluent validation check, and therefore not adding the error code into the response to be picked up by the front end.
I understand the nature of the non-nullable field would indicate that this should never be null, however that a dotnet centric thing, and I don't want to have to make the field nullable, when it shouldn't be.
But I want to be able to explicitly verify that a client that incorrectly passes a null value (which would be a valid JSON object) is still returned the appropriate error code as we've designed.
Is there a way to disable this automatic model validation within asp.net and explicitly rely only on our calls to the fluent validation methods?
Thanks,
Justin
Источник: https://stackoverflow.com/questions/781 ... null-value