Joper
Joper

Reputation: 8209

How to get User.Identity working outside controller

I have separate project with some of my custom ASP.NET MVC helpers

In one of my helpers I need to check user identity.

How may I get User.Identity working there?

By default it is living in System.Security.Principal in interface called interface IPrincipal

Upvotes: 19

Views: 12403

Answers (2)

Zoka
Zoka

Reputation: 2352

More easily you may access it by:

HttpContext.Current.User.Identity

So the HttpContext.Current is the trick.

Upvotes: 56

DanielB
DanielB

Reputation: 20210

The HtmlHelper has the current ViewContext and via HttpContext you'll get the User object for the current User. In your extension Method you can use this

public static bool MyHelper(HtmlHelper helper)
{
    var userIdentity = helper.ViewContext.HttpContext.User.Identity;
    // more code
}

Upvotes: 13

Related Questions