You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 8中如何在TypeFilterAttribute中获取控制器参数值

在.NET Core 8的TypeFilterAttribute过滤器中获取Action参数值

你目前只定义了继承TypeFilterAttribute的标记类,还需要实现具体的过滤器逻辑类,才能获取Action的参数值。以下是完整实现方案:

1. 实现具体的过滤器逻辑类

创建实现IAsyncActionFilter的过滤器类,通过构造函数接收参数名,并在Action执行流程中获取对应参数的值:

using Microsoft.AspNetCore.Mvc.Filters;

public class FileDocumentExistFilter : IAsyncActionFilter
{
    private readonly string _parameterName;

    // 接收从Attribute传递过来的参数名
    public FileDocumentExistFilter(string parameterName)
    {
        _parameterName = parameterName;
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // 从ActionArguments字典中获取指定参数的值
        if (context.ActionArguments.TryGetValue(_parameterName, out var parameterValue))
        {
            var fileDocumentValue = parameterValue as string;
            if (!string.IsNullOrEmpty(fileDocumentValue))
            {
                // 在这里编写你的业务逻辑,比如校验文件是否存在
                // 示例:Console.WriteLine($"获取到的参数值:{fileDocumentValue}");
            }
        }

        // 继续执行后续的Action或过滤器
        await next();
    }
}

2. 原Attribute类保持不变

你之前定义的FileDocumentExistFilterAttribute可以直接使用,它负责将参数传递给实际的过滤器类:

using Microsoft.AspNetCore.Mvc;

public class FileDocumentExistFilterAttribute : TypeFilterAttribute
{
    public FileDocumentExistFilterAttribute(string file = null)
        : base(typeof(FileDocumentExistFilter))
    {
        Arguments = new object[] { file };
    }
}

3. 控制器代码使用示例

你的控制器Action代码无需修改,保持原有写法即可:

[FileDocumentExistFilterAttribute(file: "fileDocument")]
public async Task<IActionResult> Index(string fileDocument)
{
    // Action逻辑
    return Ok();
}

关键说明

  • ActionExecutingContext.ActionArguments是一个字典,存储了当前Action的所有参数名和对应的值,通过你传入的参数名就能精准获取目标值。
  • 如果需要在Action执行后处理逻辑,可以在await next();之后编写代码,此时ActionExecutedContext会包含Action的执行结果。

内容的提问来源于stack exchange,提问作者Hậu tran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:09:59