Asp.Net Core在Startup文件中获取appsettings.json的内容

在appsettings.json中定义一个Mykey

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "MyKey": "appsettings.json MyKey"
}

在Startup.cs中获取appsettings.json中定义的Mykey值并输出

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace StudentManagement
{
    public class Startup
    {

        //定义一个私有并且不可修改的变量
        private readonly IConfiguration _configuration;

        //依赖注入
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                //获取appsettings.json的key值
                var configval = _configuration["MyKey"];
                await context.Response.WriteAsync(configval);
            });
        }
    }
}
后端开发

一个很好用的 PHP 加密解密模块

2022-4-5 17:31:18

后端开发

ASP.NET Core的中间件

2022-4-11 10:36:48

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索