1. 程式人生 > 其它 >LiveChart應用筆記-折線圖新增任意資料

LiveChart應用筆記-折線圖新增任意資料

ASP.NET Core的處理流程是一個管道,而中介軟體是裝配到管道中的用於處理請求和響應的元件。中介軟體按照裝配的先後順序執行,並決定是否進入下一個元件。中介軟體管道的處理流程如下圖(圖片來源於官網):

Use方法

使用方法:.net core web應用程式中,在Startup.cs中的Configure方法中加入如下程式碼配置中介軟體

            #region 使用Use裝配中介軟體到請求處理管道中
            app.Use(async (context, next) =>
            {
                if (!context.Response.HasStarted)
                {
                    Console.WriteLine(
"MyMiddleware1 Before next"); // 等待下一個中介軟體處理完成 await next(); Console.WriteLine("MyMiddleware1 after next"); } }); app.Use(async (context, next) => { if (!context.Response.HasStarted) { Console.WriteLine(
"MyMiddleware2 Before next"); // 等待下一個中介軟體處理完成 await next(); Console.WriteLine("MyMiddleware2 after next"); } }); #endregion

這時使用的Use擴充套件方法定義如下

public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)

Run方法

使用方法:同樣在Startup.cs中的Configure方法中加入如下程式碼

            #region 使用Run
            app.Run(async context => {
                await context.Response.WriteAsync("Hello from 2nd delegate.");
            });
            #endregion

頁面執行效果:

自定義中介軟體類

自定義中介軟體類有如下約定:

自定義的中介軟體類如下:

    #region 第1步:自定義中介軟體類
    public class MyMiddleware1
    {
        private readonly RequestDelegate _next;

        // 約定1:具有引數型別為RequestDelegate的公共建構函式
        public MyMiddleware1(RequestDelegate next)
        {
            this._next = next;
        }

        // 約定2:具有Invoke/InvokeAsync的公共方法,第一個引數型別為HttpContext ,返回Task
        // 如果中介軟體裡面需要使用其他範圍內服務,請將這些服務新增到 Invoke 方法的簽名
        public async Task Invoke(HttpContext context, IService1 service1)
        {
            service1.TestMethod();

            await _next(context);
        }
    }
    #endregion

    #region  第2步:定義中介軟體擴充套件方法,公開中介軟體
    public static class MiddlewareExtensions
    {
        public static IApplicationBuilder UseMyMiddleware1(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyMiddleware1>();
        }
    }
    #endregion

    #region 第3步:定義中介軟體使用的依賴服務
    public interface IService1 {
        void TestMethod();
    }

    public class Service1 : IService1
    {
        public void TestMethod()
        {
            Console.WriteLine("Service1");
        }
    }
    #endregion

    #region 第4步:在擴充套件方法中新增依賴服務註冊
    public static class IServiceCollectionExtension
    {
        public static IServiceCollection AddService1(this IServiceCollection services)
        {
            return services.AddScoped<IService1, Service1>();
        }
    }
    #endregion

在Startup中的ConfigureServices方法中註冊服務

            #region 第5步,註冊服務
            services.AddService1();
            #endregion

在Startup中的Configure方法中使用中介軟體

            #region 第6步:在Configure中使用自定義的中介軟體
            app.UseMyMiddleware1();
            #endregion

參考連結:

https://www.cnblogs.com/youring2/p/10924705.html