C#从ASP.NET核心中的appsettings获取值 [英] C# get values from appsettings in ASP.NET core

查看:227
本文介绍了C#从ASP.NET核心中的appsettings获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写asp.net核心的web api并尝试从appsettings.jsonAppSettings读取值并得到错误非静态字段,方法或属性需要对象引用。



appsettings.json

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"
    }
}





启动.cs



Startup.cs

public IConfiguration Configuration { get; }

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





我尝试过:



当我尝试阅读用户名&安全类中的密码appsettings.json,如下所示。我遇到非静态字段,方法或属性需要对象引用。





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;
        }
    }
}

推荐答案

如果您的登录方式不可能是静态的你使用了类属性



从方法中删除静态
Your Login Method cant be static if you have use the class Property

Remove static from the method


这篇关于C#从ASP.NET核心中的appsettings获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆