逻辑:增加一个自定义注解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>();
        }
    }
}

 

posted on 2024-08-21 16:23  邢帅杰  阅读(9)  评论(0编辑  收藏  举报