.Net 6 如何检测动作过滤器在控制器或动作方法上

问题描述 投票:0回答:1

我有一个像这样的动作过滤器:

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

我将属性放在控制器上,如下所示(我知道为此目的,您需要使用 IFilterFactory 或 ServiceFilter,但为了简单起见,我删除了它们):

[Test]
public class FileController : BaseApiController

或者对于操作方法:

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

所以我的问题是如何检测此属性是否在 .net 6 中的控制器作用域或操作作用域中执行?

更新:我的解决方案

这是我的仓库: https://github.com/sa-es-ir/DotNet.RateLimit

我添加了一个枚举来指定范围,如下所示:

public enum RateLimitScope
    {
        /// <summary>
        /// Rate limit will work on each action
        /// </summary>
        Action,

        /// <summary>
        /// Rate limit will work on the entire controller no matter which action calls
        /// </summary>
        Controller
    }

因此默认情况下位于 Action 范围内,直到您明确将其设置为位于 Controller 上。

asp.net-core .net-6.0 action-filter
1个回答
0
投票

此代码将对您有所帮助;

 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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.