asp.net-core.net-coreaction-filter

Pass argument to a Controller from Action Filter


Can I pass an argument from Action Filter to a controller and specifically through the parameters (in ASP.NET Core) ?

For example:

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

And

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

    }
}

Solution

  • you can use

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

    for updating existing action parameter. If you need to add new parameter, then

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

    then you can reach it through Controller Action