星期六, 4月 23, 2022

[WebApi Core] Filters - Response Headers 資訊

Filters in ASP.NET Core 內發現 ActionFilter 應用,可以把資訊打在 Header 內回傳,順道了解那些資訊可以透過 ActionExecutingContext 抓出來 

建立 ResponseHeaderAttribute

查資料時發現一個小應用,透過 Stopwatch 來偵測 Action 執行時間,一併紀錄下來
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()
        {

        }
    }
}

實際測試

透過 Postman 來進行測試,Header 資訊如下圖

[WebApi Core] Filters - Response Headers 資訊

沒有留言:

張貼留言