.net跳過某一箇中介軟體,在中介軟體中獲取自定義註解Attribute進行判斷。

邢帅杰發表於2024-08-21
邏輯:增加一個自定義註解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>();
        }
    }
}

相關文章