简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM