主要是在中介軟體中獲取自定義註解。
自定義註解
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>(); } } }