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);
}

posted @ 2020-05-15 13:46  HKBlog  阅读(128)  评论(0编辑  收藏  举报