首页 > 其他分享 >依赖注入之IConfiguration 访问appSetting.json

依赖注入之IConfiguration 访问appSetting.json

时间:2024-02-02 11:14:34浏览次数:38  
标签:IConfiguration Database Server appSetting json User cnps mis configuration

(1)创建NET6 Webapi

(2)appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AppSettings": {
    //单库
    "ConnectionString": "Server=cnps-mis-yfw;User Id=sa;Password=123;Database=northwind;"
  },
  "DBS": [
    //多库(数组)
    {
      "dbid": "0",
      "conn": "Server=cnps-mis-yfw;User Id=sa;Password=123;Database=northwind1;"
    },
    {

      "dbid": "1",
      "conn": "Server=cnps-mis-yfw;User Id=sa;Password=456;Database=northwind2;"
    },
    {
      "dbid": "2",
      "conn": "Server=cnps-mis-yfw;User Id=sa;Password=789;Database=northwind3;"
    }
  ],
  "Settings": {
    //对象
    "Name": "test123",
    "IsValid": true,
    "Counter": 123
  },
  "MulConn": {
    "code": "200",
    "msg": "ok",
    "data": [
      {
        "dbid": "0",
        "conn": "Server=cnps-mis-yfw;User Id=sa;Password=123;Database=northwind1;"
      },
      {
        "dbid": "1",
        "conn": "Server=cnps-mis-yfw;User Id=sa;Password=456;Database=northwind2;"
      },
      {
        "dbid": "2",
        "conn": "Server=cnps-mis-yfw;User Id=sa;Password=789;Database=northwind3;"
      }
    ]
  }
}
View Code

(3)program.cs

IConfiguration configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .Build();

var builder = WebApplication.CreateBuilder(args);

//builder.Services.AddSingleton(configuration);
//或
builder.Services.AddSingleton<IConfiguration>(configuration);
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
View Code

(4)UserController.cs

//using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
//using Microsoft.Extensions.Configuration;
//using static System.Collections.Specialized.BitVector32;
//using Microsoft.Extensions.Configuration.Json;
//using static webapi02.Controllers.UserController;

namespace webapi02.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        public UserController(IConfiguration config)
        {
            _configuration = config;
        }

        [HttpGet("[action]")]
        public IActionResult SayHello()
        {
            //(01)
            string? connstr = _configuration["AppSettings:ConnectionString"];
            string? connstr2 = _configuration.GetValue<string>("AppSettings:ConnectionString");
            //结果:Server=cnps-mis-yfw;User Id=sa;Password=123;Database=northwind;
            //(02)           
            List<dbconfig> list1 = new List<dbconfig>();
            _configuration.Bind(string.Join(":", new string[] { "DBS" }), list1);
            //或
            List<dbconfig> list2 = new List<dbconfig>();           
            _configuration.Bind(string.Join(":", new string[] { "MulConn", "data" }), list2);
          
            //(03)
            var list3 = new List<dbconfig>();          
            _configuration.GetSection("MulConn:data").Bind(list3);
            //或
            var list4 = new List<dbconfig>();
            _configuration.GetSection("MulConn").Bind("data",list4);
            //(04)
            var settings = new Settings();           
            _configuration.GetSection("Settings").Bind(settings);

            return new JsonResult(list1);
            //return new JsonResult(settings);
            //list1~list4结果:
            //[
            //  {
            //    "dbid": "0",
            //    "conn": "Server=cnps-mis-yfw;User Id=sa;Password=123;Database=northwind1;"
            //  },
            //  {
            //    "dbid": "1",
            //    "conn": "Server=cnps-mis-yfw;User Id=sa;Password=456;Database=northwind2;"
            //  },
            //  {
            //    "dbid": "2",
            //    "conn": "Server=cnps-mis-yfw;User Id=sa;Password=789;Database=northwind3;"
            //  }
            //]
            //settings结果
            //{
            //  "name": "test123",
            //  "isValue": false,
            //  "counter": 123
            //}
        }
        public class dbconfig
        {
            public string dbid { get; set; }
            public string conn { get; set; }
        }
        public class Settings
        {
            public string Name { get; set; }
            public bool IsValue { get; set; }
            public int Counter { get; set; }
        }
    }
}
View Code

(5)结果

 

标签:IConfiguration,Database,Server,appSetting,json,User,cnps,mis,configuration
From: https://www.cnblogs.com/rollydoc/p/18002775

相关文章

  • Python3 JSON
    PythonJSON转换 python3的json.loads不支持encoding#python3.11JSON序列化、反序列化importjsondefdata=’{\"Message":"消息", \"Timestamp":"时间戳" \}' #字符串转换编码集为UTF-8json_str=data.encode('ut......
  • 第17天:信息打点-语言框架&开发组件&FastJson&Shiro&Log4j&SpringBoot等
    框架:简单代码的一个整合库,如果使用框架就只需要学习使用框架调用即可如:文件上传功能是需要很多代码来实现的,框架把这个代码进行封封装,调用即可影响:如果采用框架开发,代码的安全性是取决于框架的过滤机制 #Python-开发框架-Django&FlaskDjango1、识别插件2、Set-Cookie:expi......
  • ASP.NET Core中JsonResult和ObjectResult的用法
    ​  在ASP.NETCore中,JsonResult和ObjectResult是两种用于返回数据的ActionResult类型,它们在控制器中用来生成HTTP响应。选择使用JsonResult还是ObjectResult取决于具体需求。如只需要返回JSON格式的数据,JsonResult是一个简单且直接的选择。如果API需要支持多种响应格式,则Obje......
  • Python | json文件和jsonl文件
    Python|json文件和jsonl文件JSON文件是使用JSON(JavaScriptObjectNotation)格式存储数据的文件。它是一种结构化的文本格式,使用键值对的方式表示数据。JSON文件通常包含一个根对象,可以包含多个嵌套的对象、数组和基本数据类型。而JSONL文件(JSONLines),则是一种每行包含一......
  • jmeter Regular Expression Extractor和JSON Extractor使用
    在Jmete中我们经常遇到需要把当前接口返回内容用于下一个接口请求,应用场景:登录接口返回的cookie或者token等,下面就简单描述一下两种提取器的使用和需要注意的事项:1、RegularExpressionExtractorApplyto:待研究;Fieldtocheck:取值的地方,ReferenceName:取得值后存放值的变量......
  • 2024年1月份更新「GIS数据」全国的GeoJSON、shp格式数据下载获取(精确到乡镇街道级)
    发现个可以免费下载全国 geojson 数据的网站,推荐一下。支持全国、省级、市级、区/县级、街道/乡镇级以及各级的联动数据,支持导入矢量地图渲染框架中使用,例如:D3、Echarts等geojson数据下载地址:https://geojson.hxkj.vip该项目github地址:https://github.com/TangSY/echarts-m......
  • fastjson 1268-jdbc
    1268-jdbc复现靶场项目是https://github.com/lemono0/FastJsonParty版本{"@type":"java.lang.AutoCloseable"回包:{"timestamp":"2024-01-31T09:45:27.342+0000","status":500,"error":"InternalS......
  • 将json对象转换成可以适应markdown格式的展示效果。
    举例数据:constcontent={"姓名":"zhangsan","name":"shkahsdhsa","2222":"22222"}页面展示:格式化后展示:实现代码constcontent={"姓名":......
  • easyui-datagrid 加载数据 方法二 ( 自定义返回值 json方式)
    效果图 html部分<tableclass="my_table"><tr><tdclass='my_dt_label'>主叫号码:</td><tdclass='my_dt_field'><inputtype='text'id='select_callerid&......
  • 11.jmeter用户定义变量、请求头管理器、json提取器、CSV导入数据
     ......