I'm building a Custom Validation Attribute in ASP.NET Core WebAPI. I need to access IDataProtector in my validator and another service I'm using to access the database. I've searched and wasn't ab;e to find any documentation for this. ActionFilters have the option of using ServiceFilter but there doesn't seem to be any option for Validation Attribute. Any ideas?
Use the GetService() method of the ValidationContext to get your database. i.e.
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
MyDbContext db = (MyDbContext) validationContext.GetService(typeof(MyDbContext));
//...
}
You can override IsValid method and use validationContext to resolve dependency:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var service = (IExternalService) validationContext.GetService(typeof(IExternalService));
// use service
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With