0

I am trying to use a filter on my WebAPI project, but for some reason the OnActionExecuting(HttpActionContext actionContext) method doesn't fire.

This is the filter class (taken from this question and modified slightly):

using System.Net;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

public class MyNoActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (IfDisabledLogic(actionContext))
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
        else
            base.OnActionExecuting(actionContext);
    }

    private bool IfDisabledLogic(HttpActionContext actionContext)
    {
        return false;
    }
}

I added the filter attribute to my controller:

[Route("api/[controller]")]
[ApiController]
[MyNoActionFilter]
public class ExampleController : ControllerBase
{...}
 

And I also added it to my Program.cs file:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddScoped(typeof(MyNoActionFilterAttribute));
...

I tried setting a breakpoint in the OnActionExecuting function but it never seems to be reached.

What am I missing here?

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12

1 Answers1

0

Try this code:

public class MyNoActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (IfDisabledLogic(actionContext))
            {
                context.Result = new NotFoundResult();
            }
            base.OnActionExecuting(context);
        }
    }

Then use this attribute on the target action directly

        [MyNoActionFilter]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

gif demo

enter image description here

More information you can refer to Filters in ASP.NET Core.

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12
  • Is there a way to get that event to fire before the UI even loads up? What I'm trying to do is a filter that allows you to completely disable (so it should be invisibile and should give you a 404 error if you try to access it) certain methods based on certain conditions that are checked before the UI loads. – Librapulpfiction Jul 17 '23 at 09:07
  • Sorry, I don't think you can use filter to hidden endpoint before swagger UI load up. – Xinran Shen Jul 17 '23 at 09:26
  • Ok, that's fine. With the code you sent, I can at least make it seem as if that method doesn't exist to the user. Thanks! – Librapulpfiction Jul 17 '23 at 09:38