.NET 8 - ASP.NET Core Web API Filters
ActionFilter, NET8,
Last updated
ActionFilter, NET8,
Last updated
using Microsoft.AspNetCore.Mvc.Filters;
namespace YourWebAPI.Filters;
public class WebApiTracker(ILogger<WebApiTracker> _logger) : IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext context)
{
var displayName = context.ActionDescriptor.DisplayName;
_logger.LogTrace($"{displayName} : BEGIN");
}
void IActionFilter.OnActionExecuted(ActionExecutedContext context)
{
var displayName = context.ActionDescriptor.DisplayName;
if (context.Exception != null)
_logger.LogCritical($"{displayName} => Exception! {context.Exception.Message}");
else
_logger.LogTrace($"{displayName} : DONE");
}
}var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(options => {
options.Filters.Add<WebApiTracker>(); //※此Filter 將會套用到全部 WebAPI。
});
...略...using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog;
namespace YourWebAPI.Filters;
public class CatchAndLog(string title) : Attribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext context)
{
Log.Debug($"{title} : BEGIN");
}
void IActionFilter.OnActionExecuted(ActionExecutedContext context)
{
//# SUCCESS
if (context.Exception == null)
{
Log.Information($"{title} : DONE");
return;
}
//# FAIL
Log.Error($"{title} => Exception! {context.Exception.Message}");
// Excepiton => 40
context.Result = new ContentResult
{
StatusCode = 400,
Content = context.Exception.Message
};
//※ 需設定此例外已處理,否則後序會再處理例外。
context.ExceptionHandled = true;
}
}using Microsoft.AspNetCore.Mvc;
namespace YourWebAPI.Controllers;
[ApiController]
[Route("[controller]")]
public class SampleController(...略...) : ControllerBase
{
[HttpPost("[action]")]
[CatchAndLog("取得天氣預報資料")] //<--- ※指定 ActionFilter。
public IEnumerable<WeatherForecast> GetWeatherForecast(int count = 3)
{
...略...
}
}