Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
}
like image 258
AbdulKarim Avatar asked Jan 02 '19 20:01

AbdulKarim


2 Answers

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

like image 52
Derviş Kayımbaşıoğlu Avatar answered Nov 09 '22 05:11

Derviş Kayımbaşıoğlu


In the attribute set values into Items collection of HttpContext:

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

And In the controller read them in the same way:

this.HttpContext.Items["DataFromAttribute"];
like image 4
Lev Z Avatar answered Nov 09 '22 05:11

Lev Z