3
votes

I am using ServiceStack (with the new API) and trying to validate a DTO. Just created some simple code to simulate a validation but it's apparently not firing or at least it's not showing the errors on the response as expected. My code is as follows:

DTO:

[Route("/users/login")]
public class UserLogin
{
    public string Email { get; set; }
    public string Password { get; set; }
}

The validator itself:

public class UserLoginValidator : AbstractValidator<UserLogin>
{
    public UserLoginValidator()
    {
        RuleSet(ApplyTo.Get, () =>
        {
            RuleFor(x => x.Email).NotEmpty().WithMessage("Please enter your e-mail.");
            RuleFor(x => x.Email).EmailAddress().WithMessage("Invalid e-mail.");
            RuleFor(x => x.Password).NotEmpty().WithMessage("Please enter your password.");
        });
    }
}

Configuring the validation in the host:

Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(UserLoginValidator).Assembly);

And the service:

public class LoginService : Service
{   
    public object Get(UserLogin request)
    {
        var response = new { SessionId = Guid.NewGuid() };
        return response;
    }
}

Is there any other config or adjustment that needs to be made to make it work?

Thanks!

1
Do you have the correct service stack version? I just pasted your code into a new ServiceStack project and it works. I got the correct validation error messages.kampsj
The version I'm using is 3.9.28.rocco
So what is the response when you make a call to "/users/login" without parameters?kampsj
@rocco the current version is v3.9.32 - always update to latest to make sure it's still an issue.mythz
@kampsj When I make a call, it returns the guid I created. It looks like the validation is not wired to the service.rocco

1 Answers

2
votes

From the documentation

Note: The response DTO must follow the {Request DTO}Response naming convention and has to be in the same namespace as the request DTO!

Try creating a class for the response

public class UserLoginResponse
{
    public UserLogin Result { get; set; }
}

And return it

public class LoginService : Service
{   
    public object Get(UserLogin request)
    {
        var response = new UserLoginResponse { Result = request };
        return response;
    }
}