Calling an AccountController function

1

I'm trying to fetch the logged-in user ID like this:

public int CurrentUserID()
{            
    return Convert.ToInt32(User.Identity.GetUserId());
}

This method is in AccountController and I want to call it from any other controller. The function is not recognized and wanted to know why and how to fix it.

    
asked by anonymous 14.12.2016 / 14:21

2 answers

3

If the method needs to be used in multiple controllers it should not be in AccountController , at least not logically. I think it's possible to do this by instantiating the controller and calling the method, but this does not seem to be very common, I've never seen anyone doing it, but I can not tell whether it's problematic or not.

There are several ways to make it work the way you want it, I'll give you an example in a simple, easy and quick way.

Create a generic controller named Controller , so all controllers created in your project will inherit it and you can use this method and others that are created) in any controller .

Note that it is necessary to use the full namespace on the right side of the colon.

public class Controller : System.Web.Mvc.Controller
{
    public int CurrentUserId()
    {
        return Convert.ToInt32(User.Identity.GetUserId());
    }
}
    
14.12.2016 / 15:34
0

Your question is with few details, but almost guaranteed that you are forgetting to add some reference (using) or the controllers may be in different namespaces.

If you are having trouble calling actions from other controllers, the RedirectToAction can assist you in these calls on different controllers.

If you are trying to call your User.Identity.GetUserId () from another controller, you need to add the reference to this location (User). (Try the famous "CTRL +." To see if VS does not solve this for you).

I hope I have helped.

    
14.12.2016 / 15:15