逻辑:增加一个自定义注解Attribute,在中间件中判断注解中是否配置了跳过该中间件,跳过则直接await _next(httpContext);
主要是在中间件中获取自定义注解。
自定义注解
主要是在中间件中获取自定义注解。
自定义注解
namespace XCGWebApp.Attributes { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class SkipMiddlewareAttribute : Attribute { public SkipMiddlewareAttribute() { SkipMiddlewareNames = ""; } public SkipMiddlewareAttribute(string names) { SkipMiddlewareNames = names; } /// <summary> /// 跳过的中间件名称,逗号分隔 /// </summary> public string SkipMiddlewareNames { get; set; } = string.Empty; } }
api示例方法,SkipMiddleware也可以加到类上。
[HttpGet] [SkipMiddleware("MyMiddleware")] public string test() { return "hello"; }
MyMiddleware示例
using XCGWebApp.Attributes; namespace XCGWebApp.MiddleWare { public class MyMiddleware { private readonly RequestDelegate _next; // 用来处理上下文请求 private readonly ILogger<MyMiddleware> _logger; public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext httpContext) { var guid = Guid.NewGuid().ToString(); bool skipThis = false; var endpoint = httpContext.GetEndpoint(); if (endpoint != null) { var skipAttribute = endpoint.Metadata.GetMetadata<SkipMiddlewareAttribute>(); if (skipAttribute != null && !string.IsNullOrEmpty(skipAttribute.SkipMiddlewareNames) && skipAttribute.SkipMiddlewareNames.Contains(this.GetType().Name)) { skipThis = true; } } //不跳过该中间件 if (!skipThis) { //do somthing... } else { _logger.LogInformation("跳过该skipmiddleware中间件"); } await _next(httpContext); } } /// <summary> /// 扩展函数 /// </summary> public static class MyMiddlewareExtensions { public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<MyMiddleware>(); } } }
分类:
.NetCore
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2018-08-21 TLS1.1升级到TLS1.2(微信小程序要求TLS1.2以上)