Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
696 views
in .Net Framework by 66 69 85

In .Net Core MVC, I'm trying to get value from app settings to MyController by implementing the below code:

public MyController(IConfiguration config)
{
    _config = config;
}
private string ApiKey = _config.GetValue<string>("ApiKey");

But I get the below error:

A field initializer cannot reference the non-static field, method, or property 'NafathController._config'


1 Answer

0 like 0 dislike
by 66 69 85
 
Best answer

Solving: A field initializer cannot reference the non-static field, method, or property

To solve this error you must change your field to a property, by adding Greater-than sign > just like that:

private string ApiKey => _config.GetValue<string>("ApiKey");
  • When using = it's create new field.
  • When using => you are creating a get-only property.
If you don’t ask, the answer is always NO!
...