Reputation: 1408
I'm trying to create an ActionFilter in aspnet vNext. Within this filter I want to access to the TempData and the ViewData (both available in Controller in previous versions).I override the method
public override void OnActionExecuting(ActionExecutingContext filterContext)
Into the filterContext
I have the controller but is an object
instead of ControllerBase
. I was expected a ControllerBase
because in previous versions of MVC the ControllerContext
(the base class of ActionExecutingContext
) was a ControllerBase
, here is the source code in codeplex. I understand that this could be because the POCO controllers.
So, the question is, how can access to the TempData and the ViewData if the controller is an object. Simply doing a downcasting (something like this (Controller)filterContext.Controller
) or there's a best way to do it.
Update
That I want to achieve if explain it in this blog post but with aspnet 5.
Upvotes: 6
Views: 2797
Reputation: 57949
To access TempData from within an action filter, you can get the service called ITempDataDictionary
from DI.
To get this service from DI, you could either do something like actionContext.HttpContext.RequestServices.GetRequiredService<ITempDataDictionary>()
from within your OnActionExecuting
method. You could also use construction inject if you like by using ServiceFilterAttribute.
NOTE:
TempData by default depends on Session
feature(i.e TempData's data is stored in Session) and so you need to few things to get it working.
Reference Microsoft.AspNet.Session
and Microsoft.Framework.Caching.Memory
packages.
In your ConfigureServices
method, do the following:
services.AddCaching();
services.AddSession();
In your Configure
method, register the Session
middleware (this is the one which creates/attaches a session to the incoming requests) and do it before registering MVC.
app.UseSession();
app.UseMvc(...)
Upvotes: 6