Click here to Skip to main content
13,627,551 members
Rate this:
 
Please Sign up or sign in to vote.
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 4 days ago
Updated 4 days ago

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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

Remove static from the method
  Permalink  
Comments
George Swan 2 days ago
   
The Login method can be simplified to
return username == AppSettingsName && password == AppSettingsPassword;
yesterday
   
Thanks @member33 & @George Swan.

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

Thank you.
member33 yesterday
   
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
yesterday
   
Thank you @member33.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web02 | 2.8.180712.1 | Last Updated 13 Jul 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100