Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a variable from an ActionFilter to a Controller Action in C# MVC?

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?

like image 771
Jon Story Avatar asked Aug 09 '16 13:08

Jon Story


People also ask

How does the controller knows which view to return?

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).

What is controller Actionresult?

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.


1 Answers

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
    }
}
like image 96
Francis Lord Avatar answered Sep 23 '22 22:09

Francis Lord