Taking a simple action filter, which checks if the user is logged in and retrieves their user ID.
public class LoginFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Authenticate (somehow) and retrieve the ID
int id = Authentication.SomeMethod();
// Pass the ID through to the controller?
.....
}
}
How could I then pass this ID through to my controller action?
[LoginFilter]
public class Dashboard : Controller
{
public ActionResult Index()
{
// I'd like to be able to use the ID from the LoginFilter here
int id = ....
}
}
Is there an equivalent to the ViewBag that would allow me to do this? Or some other technique that allows me to pass variables and objects between the filter and the controller action?
MVC by default will find a View that matches the name of the Controller Action itself (it actually searches both the Views and Shared folders to find a cooresponding View that matches). Additionally, Index is always the "default" Controller Action (and View).
An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result. RedirectResult - Represents a redirection to a new URL.
I believe ActionExecutingContext
contains a reference to the calling controller. Using this mixed with a custom controller class derived from the base Controller
class to then store the id
as an instance variable of the controller would probably do it.
Custom controller
Public Class MyController : Controller
{
Public int Id {get;set;}
}
LoginFilter
public class LoginFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Authenticate (somehow) and retrieve the ID
int id = Authentication.SomeMethod();
((MyController)filterContext.Controller).Id = id;
//Assign the Id by casting the controller (you might want to add a if ... is MyController before casting)
}
}
Controller
[LoginFilter]
public class Dashboard : MyController
{
public ActionResult Index()
{
//Read the Id here
int id = this.Id
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With