本文介绍了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;
}
}
}
推荐答案
这篇关于C#从ASP.NET核心中的appsettings获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!