zoukankan      html  css  js  c++  java
  • .Net Core 创建和使用中间件

    1. 定义中间内容

    1.1 必须有一个RequestDelegate 委托用了进入一个中间件

    1.2 通过构造函数设置这个RequestDelegate委托

    1.3 必须有一个方法Task Invoke,在这个方法里编写中间件内容最后执行RequestDelegate委托

    using Microsoft.AspNetCore.Http;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Haos.Develop.CoreTest
    {
        public class TestMiddleware
        {
            protected RequestDelegate Next;
    
            /// <summary>
            /// 参数
            /// </summary>
            public string Str { get; set; }
    
            public TestMiddleware(RequestDelegate next,string s)
            {
                Next = next;
                Str = s;
            }
    
            public virtual Task Invoke(HttpContext context)
            {
                context.Response.WriteAsync("this is test string");
                return Next(context);
            }
        }
    }

    2. 编写一个扩展方法用来添加到程序中

    using Haos.Develop.CoreTest.Service;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.Extensions.DependencyInjection;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Haos.Develop.CoreTest
    {
        public static class Extension
        {
            public static IApplicationBuilder UserTestMiddleWare(this IApplicationBuilder app, string str)
            {
                return app.UseMiddleware<TestMiddleware>(str);
            }
        }
    }

    3.  在Startup添加中间件

    // 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.UserTestMiddleWare("this is test param");
                //直接添加中间件方式
                app.Use((context, next) =>
                {
                    context.Response.WriteAsync("this is test");
                    return next();
                });
            }
  • 相关阅读:
    GIT里 SSH和HTTPS的区别
    迷宫 DFS 算法
    全排列 DFS 模板
    独立岛问题的BFS,DFS求解
    红丝绒蛋糕
    BFS,DFS伪代码
    【转】一个时代的剪影----汉
    AlbertRender --- 实时&离线全局光照渲染器(一)
    【linux驱动笔记】linux模块机制浅析
    【linux驱动笔记】字符设备驱动相关数据结构与算法
  • 原文地址:https://www.cnblogs.com/haosit/p/7754257.html
Copyright © 2011-2022 走看看