.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();
            });
        }
原文地址:https://www.cnblogs.com/haosit/p/7754257.html