Bộ lọc hành động (Action Filters) được sử dụng để thêm logic bổ sung trước hoặc sau khi thực thi phương thức hành động. Các phương thức OnActionExecuting và OnActionExecuted cho phép chúng ta chèn logic trước và sau khi một phương thức hành động được thực thi.
Tạo LogAttribute triển khai ActionFilterAttribute
Chúng ta sẽ tạo một LogAttribute kế thừa từ ActionFilterAttribute để ghi lại thông tin trước và sau khi phương thức hành động thực thi.
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(
"Phương thức hành động {0} đang thực thi lúc {1}",
actionContext.ActionDescriptor.ActionName,
DateTime.Now.ToShortDateString()),
"Web API Logs");
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
Debug.WriteLine(string.Format(
"Phương thức hành động {0} đã thực thi lúc {1}",
actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
DateTime.Now.ToShortDateString()),
"Web API Logs");
}
}
}
Áp dụng LogAttribute cho Controller Action
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
[Log]
public IHttpActionResult Get()
{
// Logic xử lý
return Ok();
}
}
}
Vì chúng ta đã sử dụng attribute Log triển khai các phương thức OnActionExecuting và OnActionExecuted, thông tin nhật ký sẽ được thêm vào bảng điều khiển gỡ lỗi (debug console).
