如何在 C# ASP.NET WebAPI 中创建用于日志记录的 LOG 过滤器?

csharpserver side programmingprogramming更新于 2025/4/17 19:52:17

操作过滤器用于在操作方法执行之前或之后添加额外的逻辑。OnActionExecuting 和 OnActionExecuted 方法用于在执行操作方法之前和之后添加我们的逻辑。

让我们创建一个 LogAttribute,它实现了 ActionFilterAttribute,它会在操作方法执行之前和之后记录一些信息。

LogAttribute−

示例

using System;
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace DemoWebApplication.Controllers{
   public class LogAttribute : ActionFilterAttribute {
      public override void OnActionExecuting(HttpActionContext actionContext){
         Debug.WriteLine(string.Format("Action Method {0} executing at {1}",
            actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()),
            "Web API Logs");
      }
      public override void OnActionExecuted(HttpActionExecutedContext
      actionExecutedContext){
         Debug.WriteLine(string.Format("Action Method {0} executed at {1}",
         actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
         DateTime.Now.ToShortDateString()), "Web API Logs");
      }
   }
}

控制器操作 −

示例

using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      [Log]
      public IHttpActionResult Get(){
         //一些逻辑
         return Ok();
      }
   }
}

由于我们使用了 Log 属性,该属性实现了 OnActionExecuting 和 OnActionExecuted 方法,因此日志信息将添加到调试控制台。


相关文章