Reputation: 169
So I have successfully implemented Account controller and various methods that come with it. I have one specific method that returns AppUser (current user)
public AppUser GetCurrentUser(){
AppUser user = UserMenager.FindById(User.Identity.GetUserId());
return user; }.
Now I don't want to have instance of UserMenager in all of my controllers (or should I?), so in my HomeController I need to render a partial view based on is user logged in or not, so I call this method
public ActionResult RightNavigation()
{
// account is instance of AccountController
AppUser user = account.GetCurrentUser();
if (user == null)
{
return PartialView("NavWhenNotLogged");
}
else
{
return PartialView("NavWhenLogged",user);
}
}
Problem is, I am getting NullException for the UserMenager instance in Account Controller :
private AppUserMenager UserMenager
{
get
{
return HttpContext.GetOwinContext().GetUserManager<AppUserMenager>();
}
}
Now I assume this is not the right way to 'share' UserMenager in different Controllers so If you could just give me 'the' way to this this.
In summary : I have Account controller that has various methods about users, etc. When I try to use one of those methods that relies on UserMenager, I get Null Exception for UserMenager.
Upvotes: 1
Views: 954
Reputation: 2818
In your Startup class you need to call the following line inside Configuration method, which puts the instance of ApplicationUserManager into OwinContext for every request.
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<UserManager>(UserManager.Create);
}
UserManager.Create() is a static method returns the instance.
Don't call controller from another controller. To get the UserManager you can do it in any controller's action:
var userManager = HttpContext.GetOwinContext().GetUserManager<UserManager>();
Upvotes: 2
Reputation: 311
Request.IsAuthenticated
In the default MVC5 project there is sample check for if user is logged in in the _LoginPartial.cshtml.
Upvotes: 0