0

In the asp.net vnext, I am getting the user claims in the Controller using the following code:

 var claimsIdentity = User.Identity as ClaimsIdentity;
        var c = claimsIdentity.FindFirst(ClaimTypes.Name);
        var temp = c.Value.ToString();

but using the same, I could not get it in my class (which used to store in DB). I am getting the following error (in User) as

The name 'User' does not exist in the current context

I tried Thread.CurrentPrincipal without success. Any help?

Karthick
  • 816
  • 1
  • 9
  • 21

1 Answers1

1

typically you would get access to User from the current HttpContext.

your class can declare a dependency on Microsoft.AspNet.Hosting.IHttpContextAccessor in its constructor to get one passed in by dependency injection. Then you can get it like this:

ClaimsPrincipal user = httpContextAccessor.HttpContext.User;
Joe Audette
  • 35,330
  • 11
  • 106
  • 99
  • So I have to declare this httpcontextAccessor in both Controller as well as in my class.. right ?... If i use the FromServices in my class as follows it gives error "Object reference not set..." Code : [FromServices] public IHttpContextAccessor _accessor { get; set; } – Karthick Jul 14 '15 at 06:55
  • your controller already has access to HttpContext so you do not need to add a dependency on IHttpContextAccessor to your controller. I suggest make it a constructor dependency not get it from service locator, I have not tried using it from service locator, but in my code it works from constructor injection – Joe Audette Jul 14 '15 at 16:04