I have a controller like this:
public class LoginController : Controller
{
private Int32 _companyID;
// My actions
}
This variable _companyID should (obviously) contain the id of the company, and this value is currently on the session. I want to get that value and set on the controller variable.
Edit: I'm using this variable because I have to check some things about this value from the session and I don't want to duplicate this code in every action. Instead, I just want to check what I need, set this value in the variable and use it inside my actions.
On WebForms, I'd simply get the value from the session in the page load event and it'd be done. But in MVC, I don't know how I do that.
My first thought was get this value in the constructor, something like that:
public LoginController()
{
_companyID = Convert.toInt32(Session["companyID"]);
}
But I discovered that session can't be accessed on constructors (it was null for me).
Then I thought about using filters, but I wasn't able to figure out how I set the value in the controller variable. I've tried in this way:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
Int32 _companyID = Convert.toInt32(HttpContext.Current.Session["idEmpresa"]);
// I couldn't pass this value directly to the controller variable
}
I've seen a few ways to pass values from filters to controllers, but all of them imply in extra code in my actions to get that value from the filter, and I don't want that. I'd like a way that I can get the desired value without change every action that I have or will have.
Is there a way to get that?
I hope that my question is clear enough. Thanks in advance!