.NET MVC user details in Controller CTOR
-
07-07-2019 - |
Question
I would like to find a way to use custom User provider within a controllers ctor in order to not have to get the user on every method (dirty)..
This is what is in my ctor but keeps returning null?
Resource oResource;
public EntityController()
{
try
{
DataEntities oEntities = new DataEntities();
oResource = oEntities.Resources.Where(c => c.user == User.Identity.Name).First();
}
catch
{
oResource = new Resource();
}
}
Solution
Override the Controller.Initialize()
method and put your code in there. The controller's context isn't available in the constructor.
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
// your code here
}
If you need the user's entity on every action, then push the behavior into a base class that your controllers inherit from.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow