Click here to Skip to main content
13,865,661 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi, I am working on writing a web api in 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": {
        "User": "test",
        "Password": "0123abcd"

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)

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;
            return false;
Updated 13-Jul-18 9:13am

1 solution

Rate this: bad
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
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

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

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