.net core 自定义中间件

2024-04-23 19:34:28 浏览数 (1)

定义中间件类

代码语言:javascript复制
public class RequestSetOptionMiddleware
    {
        private readonly RequestDelegate next;
        public RequestSetOptionMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            await next(httpContext);
        }
    }

这里保留了必须存在的部分,命名应遵守规范xxxxxMiddleware

编写启动中间件类

代码语言:javascript复制
    public static class SimpleLogExtension
    {
        /// <summary>
        /// 启动中间件
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseSimpleLog(this IApplicationBuilder  builder)
        {
            return builder.UseMiddleware<SimpleLogMiddleware>();
        }
    }

该方法为固定格式,命名应遵守xxxxxExtension,UseMiddleware中为中间件的名称

Startup中Configure方法中添加

代码语言:javascript复制
	app.UseRequestSetOption();

0 人点赞