简体   繁体   中英

.Net 6 How detect action filter is on Controller or Action method

I have an action filter like this:

 public class TestAttribute : IAsyncActionFilter, IOrderedFilter
  {
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
      {
        var onController= ?//here I want to detect whether attribute is on controller or action
      }

    public int Order { get; }
  }

And I put attribute on controller like this (I know for sake of this purpose you need to use IFilterFactory or ServiceFilter but I removed them for simplicity):

[Test]
public class FileController : BaseApiController

Or for Action methods:

[Test]
public async Task<ActionResult<FileResponse>> UploadAsync()

So my question is how to detect this attribute is execute for controller scope or action scope in .net 6?

This code will help you;

 public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var currentFilter = context.ActionDescriptor
            .FilterDescriptors
            .FirstOrDefault(filterDescriptor => ReferenceEquals(filterDescriptor.Filter, this));


        if (currentFilter == null)
        {
            return;
        }

        if (currentFilter.Scope == FilterScope.Action)
        {
            //..
        }

        if (currentFilter.Scope == FilterScope.Controller)
        {
            //...
        }

        await next();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM