ASP.NET Core 中間件獲取控制器方法中的自定義特性


為了實現自己的操作日志記錄功能,我有個思路:

  1. 自定義特性ActionAttribute;
  2. 在每個控制器方法上加上自定義特性;
  3. 通過中間件,在每個控制器方法執行完后,獲取該特性信息,寫入數據庫;

首先,自定義特性ActionAttribute.cs

    public class ActionAttribute : Attribute
    {
        public string ActionName { get; set; }

        public ActionAttribute(string actionName)
        {
            ActionName = actionName;
        }
    }

自定義中間件類:ActionLogMiddleware.cs

    public class ActionLogMiddleware
    {
        private readonly RequestDelegate _next;

        private readonly ActionLogService _service;

        public ActionLogMiddleware(RequestDelegate next, ActionLogService actionLogService)
        {
            _next = next;
            _service = actionLogService;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var endpoint = GetEndpoint(context);
            var username = "未知用戶";
            
            if (endpoint != null)
            {
                var actionAttribute = endpoint.Metadata.GetMetadata<ActionAttribute>();
                if (actionAttribute != null)
                {
                    var actionName = actionAttribute.ActionName;
                    ActionLog log = new ActionLog
                    {
                        Action = actionName,
                        ActionTime = DateTime.Now,
                        Username = username,
                        IP = ip,
                    };
                    await _service.Add(log);
                }
                
            }
            
            await _next(context);
        }

        public static Endpoint GetEndpoint(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return context.Features.Get<IEndpointFeature>()?.Endpoint;
        }
    }

擴展方法,方便激活自定義中間件:ActionLogMiddlewareExtensions.cs

    public static class ActionLogMiddlewareExtensions
    {
        public static IApplicationBuilder UseActionLog(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ActionLogMiddleware>();
        }
    }

最后,在Startup.cs中激活自定義中間件
app.UseActionLog();

使用方法,在控制器的各個方法上加上【ActionAttribute】

        [Action("刪除公告")]
        public async Task<ActionResult<int>> Delete(int id)
        {
            var model = await _service.GetById(id);
            if (model == null)
            {
                return NotFound();
            }
            return await _service.Delete(model);
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM