Override http status code from validator

I have the following DTO:

public class SomethingRequest {
     public string Code { get; set; }
}

Code must be unique, so I created a validator that checks if there is already a record with the provided code, for example,

public class SomethingValidator: AbstractValidator<SomethingRequest> 
{
    public SomethingValidator(ISomethingRepository repo) {
         RuleFor(something => something.Code).Must(BeUnique);
    }

    private bool BeUnique(string code) { ... uniqueness check... }
}

Since I use the validation function, the validator is automatically connected for all methods using SomethingRequest, which is really great.

If the condition fails, I would like to return an 409 ConflictHTTP status code, but it 400 Bad Requestalways returns.

So the questions are:

  • Am I using the vaidation function incorrectly? (that is, automatic validators were not intended to be used to verify application logic).
  • If this is not the case, are there any ways to override the status code 400 BadRequestfrom the validator?
+4
2

? ( )

, - , , , . .

, ErrorResponseFilter, -, , .

ServiceStack:

public class VerifySomethingCodeAttribute : Attribute, IHasRequestFilter
{
    IHasRequestFilter IHasRequestFilter.Copy()
    {
        return this;
    }

    public int Priority { get { return int.MinValue; } }

    public void RequestFilter(IRequest req, IResponse res, object requestDto)
    {
        SomethingRequest somethingRequestDto = requestDto as SomethingRequest;
        if(somethingRequestDto == null)
            return;

        // Verify the code
        // Replace with suitable logic
        // If you need the database your wire it up from the IoC
        // i.e. HostContext.TryResolve<IDbConnectionFactory>();
        bool isUnique = ...

        if(!isUnique)
            throw HttpError.Conflict("This record already exists");
    }
}

DTO:

[VerifySomethingCode]
public class SomethingRequest {
    public string Code { get; set; }
}

, DTO , , . .

, .

+2

1) , , , , . . , , .

2) 400 BadRequest, ErrorResponseFilter :

Plugins.Add(new ValidationFeature
{
    ErrorResponseFilter = CustomValidationError
});

...

private object CustomValidationError(ValidationResult validationResult, object errorDto)
{
    var firstError = validationResult.Errors.First();
    return new HttpError(HttpStatusCode.Conflict, firstError.ErrorCode, firstError.ErrorMessage);
}

, , , , , dto/service, - . 1.

+3

Source: https://habr.com/ru/post/1534251/


All Articles