Skip to content

Instantly share code, notes, and snippets.

@Whistler092
Created May 8, 2021 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Whistler092/b166cf58bdea3ad915326af5ebae27c0 to your computer and use it in GitHub Desktop.
Save Whistler092/b166cf58bdea3ad915326af5ebae27c0 to your computer and use it in GitHub Desktop.
Action Filter y ExceptionFilter
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
[ServiceFilter(typeof(MyActionFilter))] // Filtro aqui
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
public class MyActionFilter : IActionFilter
{
private readonly ILogger<MyActionFilter> logger;
public MyActionFilter(ILogger<MyActionFilter> logger)
{
this.logger = logger;
}
public void OnActionExecuting(ActionExecutingContext context)
{
logger.LogInformation("Antes de ejecutar la accion");
}
public void OnActionExecuted(ActionExecutedContext context)
{
logger.LogInformation("Despues de ejecutar la accion");
}
}
using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
public class MyExceptionFilter : ExceptionFilterAttribute
{
private readonly ILogger<MyExceptionFilter> logger;
public MyExceptionFilter(ILogger<MyExceptionFilter> logger)
{
this.logger = logger;
}
public override void OnException(ExceptionContext context)
{
logger.LogError(context.Exception, context.Exception.Message);
base.OnException(context);
}
}
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyActionFilter>();
services.AddControllers(options =>
{
options.Filters.Add(typeof(MyExceptionFilter));
});
//...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment