代码之家  ›  专栏  ›  技术社区  ›  Szyszka947

中间件中的GetEndpoint()始终为null

  •  0
  • Szyszka947  · 技术社区  · 4 年前

    我有如下中间件:

    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);
        }
    }
    

    和程序.cs:

    services.AddTransient<XChaCha20Poly1305EncryptionMiddleware>();
    
    services.AddControllersWithViews();
    
    var app = builder.Build();
    app.UseRouting();
    
    app.UseMiddleware<XChaCha20Poly1305EncryptionMiddleware>();
    

    但我总是有一个例外 context.GetEndpoint() in中间件为空。我正在使用NET 6。那么,如何在中间件中检查方法属性呢?现在这可能吗?我使用了HansElsen的答案,但它对我不起作用: asp.net core check route attribute in middleware

    0 回复  |  直到 4 年前
        1
  •  3
  •   davidfowl    4 年前

    您不需要调用UseRouting,也不需要调用UseEndpoints,这些都是新主机隐含的。端点选择发生在路由匹配时(或由其他代码手动设置,但默认情况下,路由是唯一执行此操作的组件)。你的其他代码是什么样子的?我没有看到任何定义的路由,也不确定请求的URL是什么。

    GetEndpoint()为null,因为没有端点。

        2
  •  1
  •   AMunim    4 年前

    我创建了一个样本 方法 属性并修饰了我的操作端点,这就是我签入中间件的方式

    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();
    
    

    这是我的输出: System.Exception: yes encryption
at StackAnswersASP.EncryptionMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) in C:\Users\HP\source\repos\StackAnswersASP\StackAnswersASP\EncryptionMiddleware.cs:line 18

    我的自定义属性

    [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();
        }
    }
    
    
    推荐文章