One of the developers in my team complained that one of the ASP.NET Web API requests was really slow and asked me to investigate the performance issue.
When I opened the solution I saw the following code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Route("validate")] | |
public async Task<IHttpActionResult> Validate([FromBody] MadModel model) | |
{ | |
var validator=new MadModelValidator(); | |
var result = validator.Validate(model); | |
return new CustomValidationResult(result); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MadModelValidator:AbstractValidator<MadModel> | |
{ | |
public MadModelValidator() | |
{ | |
RuleFor(o => o).MustAsync(async (o) => await CheckIdNumberAlreadyExist(o.Id)); | |
//Removed the other rules | |
} | |
} |
Do you notice what’s wrong?
The problem is that inside the validator an async call is done where if you look at the controller the validator is invoked in a synchronous way. This causes the API to hang as ASP.NET keeps waiting for a result that is never returned.
The solution was simple; just switch to the ValidateAsync method and await the result in the controller:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Route("validate")] | |
public async Task<IHttpActionResult> Validate([FromBody] MadModel model) | |
{ | |
var validator=new MadModelValidator(); | |
var result = await validator.ValidateAsync(model); | |
return new CustomValidationResult(result); | |
} |