Search code examples
c#.netoopasp.net-web-api2dto

DTO constructor argument validation and WebApi response


If I develop a WebApi action-method

[Route]
public string Put([FromBody]MyClass value)

is it realy bad idea to use MyClass class that has parameter validation in constructor like:

public MyClass(string value)
{
    if (!_pattern.IsMatch(value))
            throw new ArgumentException($"Value should match RegEx: {_pattern}", nameof(value));
}

So on a wrong request it throws exception from JsonMediaTypeFormatter.ReadFromStreamAsync that occures out of controller or action filters so I have not found the way to respond the client with real problem description from ArgumentException message.

Is it right that even such argument check has not place in DTO which the only allowed in WebApi and for real (domain model) MyClass should be created corresponding simple contract class without any checks at all?


Solution

  • Create an ErrorDto with a structured message from the API. Having an ExceptionFilter to handle this is common practice.

    In terms of validation feedback, you might want to have a look at this article by Martin Fowler about avoiding to use exceptions as an approach to validation.

    That being said, you might find this library interesting.