Using the .net core mvc appsettings.json profile

Using the configuration file is mainly used in two ways

1. Direct weakly typed data 

2. using strongly typed data (the data to the class mapping configuration)

Direct weakly typed data 

In appsetings.json file to create a new node to achieve two nodes TestObj weakly typed read TestObjTwo type of mapping used to achieve strong

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"TestObj": {
"ParamOne": "asp.net"
},
"TestObjTwo": {
"ParamOne": "asp.net",
"ParamTwo": "asp.netCore",
"Num": 60
}
}

 

 

 

For weakly typed string acquisition, you need IConfiguration Configuration Example of Interface Type

 

 

 Add Property public IConfiguration Configuration {get;}

public HomeController(ILogger<HomeController> logger, IOptions<TestOptions> t, IConfiguration configuration)
{
_logger = logger;
T = t;
Configuration = configuration;

// weak type
var Param = Configuration [ "TestObj: ParamOne"];

// strong type
var ParamTwo = T.Value.ParamTwo;
var = ParamOne T.Value.ParamOne;
var T.Value.Num the Num =;
}

 

Injection IConfiguration configuration via the constructor

Use var Param = Configuration [ "TestObj: ParamOne"]; weak type data read

Using strongly typed data (the data to the class mapping configuration)

A new category to be used as a map to the class should be created as class jappsetings.json profile should correspond to the type of model parameters

 

 

public class TestOptions
{
public int Num { get; set; }
public string ParamTwo { get; set; }
public string ParamOne { get; set; }
}

Add the configuration service in ConfigureServices

 

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.Configure<TestOptions>(Configuration.GetSection("TestObjTwo"));
}

 

homecontroller corresponding attribute added public IOptions <TestOptions> T {get;}

Injected into the constructor

public HomeController(ILogger<HomeController> logger, IOptions<TestOptions> t, IConfiguration configuration)
{
_logger = logger;
T = t;
Configuration = configuration;

// weak type
var Param = Configuration [ "TestObj: ParamOne"];

// strong type
var ParamTwo = T.Value.ParamTwo;
var = ParamOne T.Value.ParamOne;
var T.Value.Num the Num =;
}

 Direct mapping strongly typed data can be obtained in appsetings.json

Guess you like

Origin www.cnblogs.com/yagamilight/p/12664191.html