1

I am currently trying to convert my company's development framework to .NET 5 from .NET framework 4.7.

In old code there are a series of custom validation attributes that inherit from System.ComponentModel.DataAnnotations.RegularExpressionAttribute.

These all have the following behaviour

  1. Check if a regular expression is specified in the config file
  2. If a regular expression is specified then pass it to the base class
  3. If no regular expression is specified, pass a hard coded regular expression to the base class.

How do I access the configuration from inside a Data Annotation Validation attribute in .NET 5.

I know I could create a static Configure method on all validation attributes and manually inject the IConfiguration on app Startup but this seems clunky and inelegant, so I'm hoping there's a better way.

I'd rather not have to pass the value from the config file in as a parameter every time I use the attribute as this somewhat defeats the point of our custom regex validation attributes and also adds the possibility of someone making a mistake and passing an incorrect value into the attribute.

In the .NET framework version access to the config file was done with configuration manager. In .NET 5 this is not really an option (as I'm trying to move away from *.config files to .NET core's more flexible system)

I've done searches for how to inject into ASP.Net core attributes but all results I found seem to relate to Actionfilter and ServiceFilter, which doesn't seem to have much relevance for Data Annotation Attributes

zeocrash
  • 636
  • 2
  • 8
  • 31
  • Does this answer your question? https://stackoverflow.com/a/29916075/264697 – Steven Feb 15 '21 at 15:10
  • The passive attributes part doesn't apply I don't think as it relates to action filter attributes not data annotations but the Humble one might. Would I access the container in the way suggested in @Usman Khan's answer, below – zeocrash Feb 15 '21 at 17:34

1 Answers1

2

You can try a variation of this:

var config = (IConfiguration)validationContext.GetService(typeof(IConfiguration));

Usman Khan
  • 676
  • 1
  • 7
  • 20
  • 1
    So override the IsValid method to Check if the config entry exists and update the regex pattern property accordingly if it does, then call the base Isvalid method? That's a really elegant way of doing it. – zeocrash Feb 15 '21 at 13:53