• Asp.NetCore3.1 WebApi 获取配置json文件中的数据


    下面只是做一个简单的测试:

    1:定义好appsetting.Json文件的配置信息如下:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "Appset01": {
        "name": "小张",
        "age": "18",
        "sex": ""
      },
      "personnel": {
        "name": "小张",
        "addr": "湖南怀化",
        "books": [
          {
            "bookid": "b001",
            "bname": "西游记"
          },
          {
            "bookid": "b002",
            "bname": "水浒传"
          }
        ]
      },
      "AllowedHosts": "*"
    }
    View Code

    2:根据内容获取或者设置实体来:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace WebApiDemo
    {
        public class Appset01
        {
            public string name { get; set; }
            public string age { get; set; }
            public string sex { get; set; }
        }
    }
    View Code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace WebApiDemo
    {
        public class Person
        {
            public string name { get; set; }
            public string addr { get; set; }
            public Book[] books { get; set; }
        }
    
        public class Book
        {
            public string bookid { get; set; }
            public string bname { get; set; }
        }
    }
    View Code

    3:Startup内容中配置好服务信息:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Options;
    
    namespace WebApiDemo
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();
                services.Configure<Person>(Configuration.GetSection("personnel"));
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IOptions<Appset01>appOptions)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseRouting();
    
                app.UseAuthorization();
    
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
        }
    }
    View Code

    4:在Controller中使用:

    using System;
    namespace WebApiDemo.Controllers
    {
        using Microsoft.AspNetCore.Mvc;
        using Microsoft.Extensions.Configuration;
        using Microsoft.Extensions.Options;
        [ApiController]
        [Route("api/[controller]")]
        public class AppSetjsonController : ControllerBase
        {
            private IConfiguration _Configuration;
            public Person _person { get; set; }
            public Appset01 _jwtobj { get; set; }
            public AppSetjsonController(IConfiguration configuration, IOptions<Person> options)
            {
                this._Configuration = configuration;
                this._person = options.Value;
            }
            [HttpGet]
            [Route("getAppSetting")]
            public ApiResult<Appset01> getAppSetting()
            {
                ApiResult<Appset01> dic = new ApiResult<Appset01>();
                try
                {
                    //BindNonPublicProperties 默认为false全部获取,true为不获取私有的字段
                    dic.data = _Configuration.GetSection("Appset01").Get<Appset01>(c => c.BindNonPublicProperties = true);
                    Console.WriteLine("addr=" + _person.addr + ",name=" + _person.name + ", book[0].name=" + _person.books[0].bname);
                    dic.message = "获取成功!";
                }
                catch (Exception ex)
                {
                    dic.message = "获取失败:" + ex.Message;
                }
                return dic;
            }
        }
    }
    View Code

    5:查询的效果展示:

     6:获取自定义路径下的json配置文件信息

    其他方法获取(下标)

      using Microsoft.Extensions.Configuration; 
    
     public IConfiguration _configuration { get; set; }
    public BasisApiResult doJson(int index)
    {
    BasisApiResult result = new BasisApiResult();
    List<Dictionary<string, string>> dict = new List<Dictionary<string, string>>();
    _configuration.GetSection("OSS").Bind(dict);
    dict[index].TryGetValue("AccessKeyId", out string qq);
    Console.WriteLine("qq=" + qq);
    result.data = qq;
    return result;
    }
    View Code
  • 相关阅读:
    走了
    地表最简单安装MySQL及配置的方法,没有之一
    周总结
    Codeforces 1323 div2题解ABC
    Code force-CodeCraft-20 (Div. 2) D. Nash Matrix 详解(DFS构造)
    LeetCode 1293. Shortest Path in a Grid with Obstacles Elimination
    LeetCode 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold
    LeetCode 1291. Sequential Digits
    LeetCode 1290. Convert Binary Number in a Linked List to Integer
    LeetCode 91. Decode Ways
  • 原文地址:https://www.cnblogs.com/Fengge518/p/12578233.html
Copyright © 2020-2023  润新知