10

我可以将参数从动作过滤器传递给控制器​​,特别是通过参数(在 ASP.NET Core 中)吗?

例如:

public class CategoryController : Controller
{
    [HttpGet]
    [ServiceFilter(typeof(ApiFilter))]
    public async Task<IActionResult> Index(string dataComingFromActionFilter)
    {
        //use dataComingFromActionFilter
    }
}

public class ApiFilter: IActionFilter 
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        //maybe something similar to
        context.sendToActionAsArgument['dataComingFromActionFilter'] = "data";

    }
}
4

3 回答 3

13

您可以使用

 context.ActionArguments["dataComingFromActionFilter"] = "data";

用于更新现有的动作参数。如果您需要添加新参数,则

context.ActionArguments.Add("dataComingFromActionFilter", "data"); 

然后您可以通过 Controller Action 到达它

于 2019-01-02T22:52:58.137 回答
4

在属性集的值放入 HttpContext 的 Items 集合中:

context.HttpContext.Items.Add("DataFromAttribute", date);

并在控制器中以相同的方式读取它们:

this.HttpContext.Items["DataFromAttribute"];
于 2019-11-07T16:33:53.963 回答
0

尝试使用下面的代码以查看它的工作原理。

public class PersonFilterAttribute: Attribute, IAsyncActionFilter
    {
        public PersonFilterAttribute()
        {
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
          context.ActionArguments.Add("personService", new PersonService("Thomas", 29,"Miami");       
          await next();
        }
    }
    
And In the controller read them in the same way:

this.HttpContext.Items["personService"];
于 2021-07-26T18:24:41.263 回答