Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am working on writing a web api in asp.net core and trying read values from appsettings.json "AppSettings" and get error "an object reference is required for the non-static field, method or property".

appsettings.json
{
    "AppSettings": {
        "User": "test",
        "Password": "0123abcd"
    }
}


Startup.cs
public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IConfiguration>(Configuration);
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}


What I have tried:

When I am trying to read the Username & Password appsettings.json in security class like below. I run into "an object reference is required for the non-static field, method or property".

public class security
{
    private AppSettings AppSettings { get; set; }

    public security(IOptions<AppSettings> settings)
    {
        AppSettings = settings.Value;
    }
    public static bool Login(string username, string password)
    {
        if (username == AppSettings.User && password == AppSettings.Password)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
Posted
Updated 13-Jul-18 8:13am

1 solution

Your Login Method cant be static if you have use the class Property

Remove static from the method
 
Share this answer
 
Comments
George Swan 15-Jul-18 0:38am    
The Login method can be simplified to
return username == AppSettingsName && password == AppSettingsPassword;
Member 12586110 16-Jul-18 12:28pm    
Thanks @member33 & @George Swan.

@member33, Could you please explain why can't AppSettings be used with static methods?

Thank you.
member33 16-Jul-18 12:52pm    
AppSettings will only get initialized when you create a new instance of your class security. When you use/ access static methods you do not create a instance of the class and thats why AppSettings was null
karthime 10-Oct-18 16:08pm    
Hi, How to instantiate class Security from controller.cs. I don't know how to pass constructor parameter to instantiate this class.
Member 12586110 16-Jul-18 13:40pm    
Thank you @member33.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900