I have Middleware as below:
public class XChaCha20Poly1305EncryptionMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var isEncryptionEnabled = context.GetEndpoint().Metadata.Any(m => m is XChaCha20Poly1305EncryptionAttribute);
if(isEncryptionEnabled)
Console.WriteLine("Test 1");
else Console.WriteLine("Test 2");
await next(context);
}
}
And Program.cs:
services.AddTransient<XChaCha20Poly1305EncryptionMiddleware>();
services.AddControllersWithViews();
var app = builder.Build();
app.UseRouting();
app.UseMiddleware<XChaCha20Poly1305EncryptionMiddleware>();
But I always get exception that context.GetEndpoint()
in middleware is null. I'm using NET 6. So how can I check method attributes in middleware? Is this now possible? I've used this HansElsen answer but it doesn't work for me:
My custom attribute
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class EncryptionAttribute: Attribute
{
}
and my controller
[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(Name = "GetWeatherForecast")]
[Encryption]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}