打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
AspNetCore基础二

管道简单实现

新建一个控制台项目,创建管道类

public class ApplicationBuilder{    /// <summary>    /// 中间件列表    /// </summary>    private static readonly IList<Func<RequestDelegate, RequestDelegate>> _components =        new List<Func<RequestDelegate, RequestDelegate>>();    /// <summary>    /// 扩展Use    /// </summary>    /// <param name="middleware">中间件</param>    /// <returns></returns>    public ApplicationBuilder Use(Func<HttpContext,Func<Task>,Task> middleware)    {        return Use(next =>        {            return context =>            {                Task SimpleNext() => next(context);                return middleware(context, SimpleNext);            };        });    }    /// <summary>    /// 原始Use    /// </summary>    /// <param name="middleware">中间件</param>    /// <returns></returns>    public ApplicationBuilder Use(Func<RequestDelegate,RequestDelegate> middleware)    {        //添加中间件        _components.Add(middleware);        return this;    }    /// <summary>    /// 生成管道方法    /// </summary>    /// <returns></returns>    public RequestDelegate Build()    {        //设置一个默认中间件        RequestDelegate app = context =>         {             Console.WriteLine("默认中间件");             return Task.CompletedTask;         };        //把独立的中间件委托串起来 然后返回反转后最后一个中间件(即第一个注册的中间件)        //至此管道才真正建立起来 每一个中间件首位相连        //主机创建以后运行        foreach(var component in _components.Reverse())        {            app = component(app);        }        return app;    }}

在main中创建中间件并放入管道中

class Program{    static void Main(string[] args)    {        var app = new ApplicationBuilder();        app.Use(async (context, next) =>        {            Console.WriteLine("中间件1号 Begin");            await next();            Console.WriteLine("中间件1号 End");        });        app.Use(async (context, next) =>        {            Console.WriteLine("中间件2号 Begin");            await next();            Console.WriteLine("中间件2号 End");        });        //调用Build生成管道         var firstMiddleware = app.Build();        //执行第一个中间件 就会依次调用下一个中间件        firstMiddleware(new HttpContext());    }}

HttpContext是Http上下文,这里没有内容,新建一个名为HttpContext类即可
RequestDelegate声明如下:

public delegate Task RequestDelegate(HttpContext context);

运行结果

中间件1号 Begin中间件2号 Begin默认中间件中间件2号 End中间件1号 End

读取配置文件信息

系统配置文件读取

  • 在appsetting.json文件中加入下面的内容
"ConnectionString": "data source=.;initial catalog=db;user id=sa",  "WebSetting": {    "WebName": "ASP.NET Core",    "Title": "Hello Title",    "Behavior": {      "IsCheckIp": true,      "MaxConnection": 300    }  }
  • 声明IConfiguration对象,在构造函数中为它赋值
private readonly IConfiguration _configuration;public Startup(IConfiguration configuration){    _configuration = configuration;}

通用读取方法


  • 直接使用_configuration获取, 子节点通过 : 获取
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IOptions<AppSetting> appOptions)  {     app.Run(async context =>     {         //通用读取方法         var conStr = _configuration["ConnectionString"];         var title = _configuration["WebSetting:Title"];     }); }

绑定配置模型对象


  • 创建配置模型
public class AppSetting{    public string ConnectionString { get; set; }    public WebSetting WebSetting { get; set; }}public class WebSetting{    public string WebName { get; set; }    public string Title { get; set; }    public Behavior Behavior { get; set; }}public class Behavior{    public bool IsCheckIp { get; set; }    public int MaxConnection { get; set; }}
  • 绑定配置模型对象,读取配置文件信息
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IOptions<AppSetting> appOptions)  {     app.Run(async context =>     {         //绑定配置模型对象         var appSetting = new AppSetting();         _configuration.Bind(appSetting);         var maxCon = appSetting.WebSetting.Behavior.MaxConnection;         //部分绑定         var webSeting = new WebSetting();         _configuration.GetSection("WebSetting").Bind(webSeting);     }); }

注册配置选项服务


  • 注册配置选项的服务
public void ConfigureServices(IServiceCollection services){    services.Configure<AppSetting>(_configuration);}
  • 读取配置文件信息
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IOptions<AppSetting> appOptions)  {     app.Run(async context =>     {         //注册配置选项服务         var a = appOptions.Value.WebSetting.Behavior.IsCheckIp;     }); }

自定义配置文件读取

  • 自定义配置文件除了不能通过IConfiguration对象读取,其他基本与系统配置文件读取方式相同
public void ConfigureServices(IServiceCollection services){    //自定义配置文件读取    var config = new ConfigurationBuilder().AddJsonFile("jsonConfig.json").Build();    //var name = config["Name"];    services.Configure<JsonConfig>(config);}

来源:https://www.icode9.com/content-1-694351.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
一步步完成迷你版的ASP.NET Core框架
NETCore 读取JSON配置文件
C# 中的应用配置
初识Core
第一章 开发体验
dotNET Core 3.X 请求处理管道和中间件的理解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服