我创建了一个样本
方法
属性并修饰了我的操作端点,这就是我签入中间件的方式
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var endpoint = context
?.GetEndpoint()
?.Metadata
?.GetMetadata<ControllerActionDescriptor>();
var encryptionEnabled = endpoint?.MethodInfo?.GetCustomAttribute<EncryptionAttribute>();
if (encryptionEnabled is null)
throw new Exception("no encryption");
else
throw new Exception("yes encryption");
await next(context);
}
以及我如何注册中间件
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<EncryptionMiddleware>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseMiddleware<EncryptionMiddleware>();
app.MapControllers();
app.Run();
这是我的输出:
我的自定义属性
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class EncryptionAttribute: Attribute
{
}
和我的控制器
[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();
}
}