Search code examples
c#asp.net-mvcasp.net-mvc-helpers

Call User.Identity.GetUserId() from Helpers with ASP.NET MVC


I'm new with ASP.NET MVC,

I moved an HTTP POST method from my controller to Helpers, and I can't call User.Identity.GetUserId() from System.Security.Principal.IIdentity library.

Why can I not use this library from the helpers? Thanks


Solution

  • The User object that you get from within the controller using User.Identity.GetUserId() is of type HttpContext.User.

    You can get get the current HttpContext by using HttpContext.Current which sits within System.Web.

    You'll need the using statement for the Extension method too.

    using Microsoft.AspNet.Identity;
    using System.Web;
    
    public class MyClass()
    {
        public void MyMethod()
        {
            // Get the current context
            var httpContext = HttpContext.Current;
    
            // Get the user id
            var userId = httpContext.User.Identity.GetUserId();
        }
    }
    

    I personally would recommend passing this value in as a parameter from your controller if you're retrieving it within your helper methods because it makes it a bit more clear that it relies on it?

    You will need to get this value from your controller and pass it as a parameter if you move the helper method into your service layer etc.