In an ASP.Net Core WebApp I want to use an ActionFilter and send information from the ActionFilter to the controller it is applied to.
MVC
For MVC I can do this
ActionFilter
public class TenantActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
//Using some sneaky logic to determine current tenant from domain, not important for this example
int tenantId = 1;
Controller controller = (Controller)context.Controller;
controller.ViewData["TenantId"] = tenantId;
}
public void OnActionExecuted(ActionExecutedContext context) { }
}
Controller
public class TestController : Controller
{
[ServiceFilter(typeof(TenantActionFilter))]
public IActionResult Index()
{
int tenantId = ViewData["TenantId"];
return View(tenantId);
}
}
It works and I can pass data back to the controller via ViewData - great.
WebApi
I want to do the same for WebApi Controllers.
The actionFilter itself can be applied, runs etc - but I cannot write to ViewData, because WebAPI inherits from ControllerBase - not from Controller (like MVC).
Question
How can I push data from my ActionFilter back to the calling ControllerBase, similar to MVC?
Notes
- ASP.Net Core 2.2 being used, but I would be surprised if a solution would not be usable in all of .Net Core.