动作过滤器在 asp.net 核心 Web API 中不工作

Action Filter is not working in asp.net core Web API

我在 ASP.NET Core 3.1 Web API.

中为 HTTP 请求验证创建了一个操作过滤器

不幸的是,它不起作用。问题必须出在控制器级别,因为在 .NET Framework 中也是如此。

CustomAuthorize.cs

public class CustomAuthorize : ActionFilterAttribute
{
    private readonly IConfiguration _configuration;

    public CustomAuthorize(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public override void OnActionExecuting(HttpActionContext context)
    {
        string secrect = _configuration.GetSection("AuthJWT").GetSection("Secrect").Value;
        var request = context.Request.Headers.GetValues("AuthJWT").FirstOrDefault();
        //Add Validation code here
        base.OnActionExecuting(context);

    }
}

家庭控制器

[Route("[controller]")]
[ApiController]
[ServiceFilter(typeof(CustomAuthorize))]
public class HomeController : ControllerBase
{       
    [HttpGet("getdata")]
    public IActionResult GetData()
    {
        return Ok("Success");
    }
}

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddControllers();

        services.AddScoped<CustomAuthorize>();

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

ActionFilterAttribute 抽象 class 包括以下要覆盖的方法:

void OnActionExecuted(ActionExecutedContext filterContext)
void OnActionExecuting(ActionExecutingContext filterContext)
void OnResultExecuted(ResultExecutedContext filterContext)
void OnResultExecuting(ResultExecutingContext filterContext)

OnActionExecuting中使用ActionExecutingContext

只需要修改CustomAuthorizeOnActionExecuting。其他代码同你.

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string secrect = _configuration.GetSection("AuthJWT").GetSection("Secrect").Value;
            
            var request = context.HttpContext.Request.Headers["AuthJWT"].FirstOrDefault();
            //Add Validation code here
            base.OnActionExecuting(context);

        }

Test of result