1. 程式人生 > >asp.net core基礎知識

asp.net core基礎知識

color hid col bubuko n) build core none http

一、配置管理

1,讀取內存配置

技術分享圖片
using System;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            Dictionary<string, string> dic = new Dictionary<string, string
>() { { "name","hunter"}, { "age","10"} }; var builder = new ConfigurationBuilder() .AddInMemoryCollection(dic)//當age沒有值的時候使用dic裏面的值 .AddCommandLine(args); var configuration = builder.Build(); Console.WriteLine($
"name:{configuration["name"]}"); Console.WriteLine($"age:{configuration["age"]}"); Console.ReadKey(); } } }
demo

技術分享圖片

2,讀取json文件

技術分享圖片
using System;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace ConsoleApp1
{
    
class Program { static void Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile("class.json"); var configuration = builder.Build(); Console.WriteLine($"no:{configuration["no"]}"); Console.WriteLine($"name:{configuration["name"]}"); Console.WriteLine("student:"); Console.WriteLine($"no:{configuration["student:0:no"]},name:{configuration["student:0:name"]}"); Console.WriteLine($"no:{configuration["student:1:no"]},name:{configuration["student:1:name"]}"); Console.ReadKey(); } } }
demo 技術分享圖片
{
  "no": "1",
  "name": "asp.net core",
  "student": [
    {
      "no": "1",
      "name": "張三"
    },
    {
      "no": "2",
      "name": "張三"
    }
  ]
}
class.json

3,讀取appsettings.json

技術分享圖片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        private IConfiguration _configuration;
        public HomeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public IActionResult Index()
        {
            Class c = new Class();
            _configuration.Bind(c);

            return View();
        }
    }
}
構造註入iconfiguration 技術分享圖片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1
{
    public class Class
    {
        public string no { get; set; }
        public string name { get; set; }
        public IEnumerable<student> student { get; set; }
    }

    public class student {
        public string no { get; set; }
        public string name { get; set; }
    }
}
Class類 技術分享圖片
{
  "no": "1",
  "name": "asp.net core",
  "student": [
    {
      "no": "1",
      "name": "張三"
    },
    {
      "no": "2",
      "name": "張三"
    }
  ]
}
appsettings.json

asp.net core基礎知識