1

I have fluent validation integrated which is working fine for POST requests model validation

But what is the best approach to attach validator to GET requests?

public async Task<IActionResult> GetV2Async(Constants.Status status, int? cafeId)

My current validators for my POST requests look like this:

 public CafeAddressRequestValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required");
        RuleFor(x => x.AddressLine1).NotEmpty().WithMessage("AddressLine1 is required");
    }
2
  • no you can't, github.com/FluentValidation/FluentValidation/issues/337 Commented Jul 16, 2020 at 1:06
  • What is your Constants.Status?The fluent validation could work well with get request.Please share more code about how did you configure fluent validation and what is the version of your asp.net core? Commented Jul 16, 2020 at 2:22

1 Answer 1

5

Here is a working demo like below:

Model:

public class Status
{
    public string Name { get; set; }
    public string AddressLine1 { get; set; }
}

Controller:

[HttpGet]
public IActionResult Get(Status status, int? cafeId)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    return Ok("Validate pass");
}

Startup.cs:

services.AddControllers()
       .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<CafeAddressRequestValidator>());

Custom FluentValidation:

public class CafeAddressRequestValidator : AbstractValidator<Status>
{
    
    public CafeAddressRequestValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required");
        RuleFor(x => x.AddressLine1).NotEmpty().WithMessage("AddressLine1 is required");
    }
}

Result: enter image description here

If you want to pass the validation,send request like:https://localhost:portNumber/yourMethod?status.name=dsfsd&status.AddressLine1=sdf:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

It helped thank you! Sorry for the delayed response I thought I had responded :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.