Calling an Accountcontroller function

Asked

Viewed 119 times

1

I am trying to fetch the logged in user ID this way:

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

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

  • 1

    How so not recognized? What is the error reported by the compiler? You are probably forgetting some reference or using...

2 answers

3


If the method needs to be used in several controllers he shouldn’t be in AccountController, at least not logically. I think it is possible to do this by instantiating the controller in question and calling the method, but this does not seem to me to be something very common, I have never seen anyone doing it, but also can not say whether it is problematic or not.

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

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

Note that it is necessary to use namespace complete on the right side of the two points.

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

0

Your question is lacking in detail, but almost guaranteed that you’re forgetting to add some reference (using) or controllers may be in separate namespaces.

If you’re having trouble calling actions from other controllers, the method Redirecttoaction can help you with these calls in different controllers.

If you are trying to call your User.Identity.Getuserid() from another controller, you need to add the reference of this location (User). (Try the famous "CTRL+ ." to see if VS doesn’t solve this for you).

I hope I’ve helped.

  • 1

    Hello Bruno, all right? So the question refers to accessing a method from another controller. One Redirecttoaction() does not fit this model. The Copy&paste It might work, but it’s something that won’t work if you use it in more places. The way I would do it is in @jbueno’s reply. When you have time, take a look and see if you agree. p

Browser other questions tagged

You are not signed in. Login or sign up in order to post.