建立 ResponseHeaderAttribute
查資料時發現一個小應用,透過 Stopwatch 來偵測 Action 執行時間,一併紀錄下來
透過 Postman 來進行測試,Header 資訊如下圖
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics;
namespace FilterSample
{
public class ResponseHeaderAttribute : ActionFilterAttribute
{
private readonly string _name;
private readonly string _value;
private readonly Stopwatch _sw = new Stopwatch();
public ResponseHeaderAttribute(string name, string value)
{
this._name = name;
this._value = value;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
_sw.Start();
}
public override void OnActionExecuted(ActionExecutedContext context)
{
string HttpMethod = context.HttpContext.Request.Method;
string ControllerName = ((ControllerActionDescriptor)context.ActionDescriptor).ControllerName;
string ActionName = ((ControllerActionDescriptor)context.ActionDescriptor).ActionName;
_sw.Stop();
TimeSpan ts = _sw.Elapsed;
_sw.Reset();
context.HttpContext.Response.Headers.Add(nameof(HttpMethod), HttpMethod);
context.HttpContext.Response.Headers.Add(nameof(ControllerName), ControllerName);
context.HttpContext.Response.Headers.Add(nameof(ActionName), ActionName);
context.HttpContext.Response.Headers.Add("RunTime", ts.ToString());
context.HttpContext.Response.Headers.Add(_name, _value);
}
}
}
套用 ResponseHeadersAttribute
使用 NET 6 WebAPI Core 專案預設 Controller - WeatherForecast,有些 Code 就刪除不顯示啦
using Microsoft.AspNetCore.Mvc;
namespace FilterSample.Controllers
{
[ApiController]
[Route("[controller]")]
[ResponseHeader("ControllerLevel", "Controller")] // 使用 ResponseHeaderAttribute
public class WeatherForecastController : ControllerBase
{
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
}
}
}
實際測試
- 參考資料
- ActionExecutedContext 類別
- ActionDescriptor 類別
- 【13.Filter】ASP.NET Core Web API 入門教學(13_4) - ActionFilter之Log紀錄
- asp.net core ActionExecutedContext 获取Request.Body内容 - 有完整 ActionExecutedContext 相關資訊可以參考