How get current user in asp.net core











up vote
58
down vote

favorite
13












I want to get current user for getting information of user such as email.
But i cant do that in asp.net core.I'm so confused
This is my code.



HttpContext almost is null in constructor of controller.
It's not good get user in each action.I Wanna get information of user once and set them into ViewData;



    public DashboardController()
{
var user = HttpContext.User.GetUserId();
}









share|improve this question




















  • 2




    Using with MVC or Web APi ?
    – Tushar
    Apr 15 '16 at 8:05






  • 1




    i'm using mvc .
    – Mehran Hafizi
    Apr 15 '16 at 8:07















up vote
58
down vote

favorite
13












I want to get current user for getting information of user such as email.
But i cant do that in asp.net core.I'm so confused
This is my code.



HttpContext almost is null in constructor of controller.
It's not good get user in each action.I Wanna get information of user once and set them into ViewData;



    public DashboardController()
{
var user = HttpContext.User.GetUserId();
}









share|improve this question




















  • 2




    Using with MVC or Web APi ?
    – Tushar
    Apr 15 '16 at 8:05






  • 1




    i'm using mvc .
    – Mehran Hafizi
    Apr 15 '16 at 8:07













up vote
58
down vote

favorite
13









up vote
58
down vote

favorite
13






13





I want to get current user for getting information of user such as email.
But i cant do that in asp.net core.I'm so confused
This is my code.



HttpContext almost is null in constructor of controller.
It's not good get user in each action.I Wanna get information of user once and set them into ViewData;



    public DashboardController()
{
var user = HttpContext.User.GetUserId();
}









share|improve this question















I want to get current user for getting information of user such as email.
But i cant do that in asp.net core.I'm so confused
This is my code.



HttpContext almost is null in constructor of controller.
It's not good get user in each action.I Wanna get information of user once and set them into ViewData;



    public DashboardController()
{
var user = HttpContext.User.GetUserId();
}






asp.net .net asp.net-identity asp.net-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 29 '16 at 8:13









Kirk

3,51322042




3,51322042










asked Apr 15 '16 at 7:54









Mehran Hafizi

5161413




5161413








  • 2




    Using with MVC or Web APi ?
    – Tushar
    Apr 15 '16 at 8:05






  • 1




    i'm using mvc .
    – Mehran Hafizi
    Apr 15 '16 at 8:07














  • 2




    Using with MVC or Web APi ?
    – Tushar
    Apr 15 '16 at 8:05






  • 1




    i'm using mvc .
    – Mehran Hafizi
    Apr 15 '16 at 8:07








2




2




Using with MVC or Web APi ?
– Tushar
Apr 15 '16 at 8:05




Using with MVC or Web APi ?
– Tushar
Apr 15 '16 at 8:05




1




1




i'm using mvc .
– Mehran Hafizi
Apr 15 '16 at 8:07




i'm using mvc .
– Mehran Hafizi
Apr 15 '16 at 8:07












7 Answers
7






active

oldest

votes

















up vote
95
down vote



accepted










User.FindFirst(ClaimTypes.NameIdentifier).Value


EDIT for constructor



Below code works:



public Controller(IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
}


Edit for RTM



You should register IHttpContextAccessor:



    public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}





share|improve this answer



















  • 1




    it works in actions.but i wanna use in constructor of controller.
    – Mehran Hafizi
    Apr 15 '16 at 8:31






  • 1




    is it possible use this in classes?
    – Mehran Hafizi
    Apr 15 '16 at 8:53






  • 1




    because of dependency injection, yes you can use
    – adem caglin
    Apr 15 '16 at 8:55






  • 1




    ClaimTypes.NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.
    – Nikolay Kostov
    Mar 7 '17 at 16:16










  • Does this work for Web Api as well as MVC?
    – Jin Izzraeel
    Dec 9 '17 at 0:37


















up vote
26
down vote













Simple way that works and I checked.



var user = await _userManager.GetUserAsync(HttpContext.User);


then you can all the properties of this variables like user.Email. I hope this would help someone.






share|improve this answer





















  • works great for me inside a controller in asp.net Core 2.0
    – jmdon
    Mar 26 at 16:59






  • 1




    what is a _userManager?
    – NullVoxPopuli
    Jul 20 at 12:23






  • 1




    In ASP.NET Core Identity, User Manager is a service provided by Dependency Inject to Create Users. See docs for more info:
    – Ahmad
    Jul 20 at 14:25




















up vote
18
down vote













Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^



// Stores UserManager
private readonly UserManager<ApplicationUser> _manager;

// Inject UserManager using dependency injection.
// Works only if you choose "Individual user accounts" during project creation.
public DemoController(UserManager<ApplicationUser> manager)
{
_manager = manager;
}

// You can also just take part after return and use it in async methods.
private async Task<ApplicationUser> GetCurrentUser()
{
return await _manager.GetUserAsync(HttpContext.User);
}

// Generic demo method.
public async Task DemoMethod()
{
var user = await GetCurrentUser();
string userEmail = user.Email; // Here you gets user email
string userId = user.Id;
}


That code goes to controller named DemoController. Won't work without both await (won't compile) ;)






share|improve this answer























  • This requires the use of Identity
    – Fraze
    Sep 27 at 17:43










  • What is ApplicationUser?
    – Mike
    Dec 13 at 15:47


















up vote
11
down vote













It would appear that as of now (April of 2017) that the following works:



public string LoggedInUser => User.Identity;


At least while within a Controller






share|improve this answer

















  • 3




    You cannot implicitly convert type 'System.Security.Principal.IIdentity' to 'string'.
    – Anthony Huang
    Mar 15 at 19:21






  • 1




    string LoggedInUser = User.Identity.Name;
    – Alic W
    Sep 1 at 3:27






  • 1




    As someone who hadn't seen the => operator used like this before, it is called an "Expression Body Definition" and is described in this documentation. Just in case future people like me are wondering.
    – Nathan Clement
    Oct 22 at 16:46


















up vote
3
down vote













My problem was to access the logged in User as an object in the cshtml file. Considering you wanted the user in ViewData, this approach might be helpful:



In the cshtml file



@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> UserManager

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
@UserManager.FindByNameAsync(UserManager.GetUserName(User)).Result.Email
</title>
</head>
<body>

</body>
</html>





share|improve this answer





















  • Any idea how you might get a navigation property to load (Company name of a company navigation property on my ApplicationUser class). Didn't see a way to include navigation properties.
    – Hunter Nelson
    Oct 2 at 5:39


















up vote
1
down vote













In addition to existing answers I'd like to add that you can also have a class instance available app-wide which holds user-related data like UserID etc.



It may be useful for refactoring e.g. you don't want to fetch UserID in every controller action and declare an extra UserID parameter in every method related to Service Layer.



I've done a research and here's my post.



You just extend your class which you derive from DbContext by adding UserId property (or implement a custom Session class which has this property).



At filter level you can fetch your class instance and set UserId value.



After that wherever you inject your instance - it will have the necessary data (lifetime must be per request, so you register it using AddScoped method).



Working example:



public class AppInitializationFilter : IAsyncActionFilter
{
private DBContextWithUserAuditing _dbContext;

public AppInitializationFilter(
DBContextWithUserAuditing dbContext
)
{
_dbContext = dbContext;
}

public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next
)
{
string userId = null;
int? tenantId = null;

var claimsIdentity = (ClaimsIdentity)context.HttpContext.User.Identity;

var userIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
if (userIdClaim != null)
{
userId = userIdClaim.Value;
}

var tenantIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == CustomClaims.TenantId);
if (tenantIdClaim != null)
{
tenantId = !string.IsNullOrEmpty(tenantIdClaim.Value) ? int.Parse(tenantIdClaim.Value) : (int?)null;
}

_dbContext.UserId = userId;
_dbContext.TenantId = tenantId;

var resultContext = await next();
}
}


For more information see my answer.






share|improve this answer






























    up vote
    -1
    down vote













    I got my solution



    var claim = HttpContext.User.CurrentUserID();

    public static class XYZ
    {
    public static int CurrentUserID(this ClaimsPrincipal claim)
    {
    var userID = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
    "UserID").Value;
    return Convert.ToInt32(userID);
    }
    public static string CurrentUserRole(this ClaimsPrincipal claim)
    {
    var role = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
    "Role").Value;
    return role;
    }
    }





    share|improve this answer





















    • While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
      – Alexander
      May 10 at 17:04











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36641338%2fhow-get-current-user-in-asp-net-core%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    7 Answers
    7






    active

    oldest

    votes








    7 Answers
    7






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    95
    down vote



    accepted










    User.FindFirst(ClaimTypes.NameIdentifier).Value


    EDIT for constructor



    Below code works:



    public Controller(IHttpContextAccessor httpContextAccessor)
    {
    var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
    }


    Edit for RTM



    You should register IHttpContextAccessor:



        public void ConfigureServices(IServiceCollection services)
    {
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }





    share|improve this answer



















    • 1




      it works in actions.but i wanna use in constructor of controller.
      – Mehran Hafizi
      Apr 15 '16 at 8:31






    • 1




      is it possible use this in classes?
      – Mehran Hafizi
      Apr 15 '16 at 8:53






    • 1




      because of dependency injection, yes you can use
      – adem caglin
      Apr 15 '16 at 8:55






    • 1




      ClaimTypes.NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.
      – Nikolay Kostov
      Mar 7 '17 at 16:16










    • Does this work for Web Api as well as MVC?
      – Jin Izzraeel
      Dec 9 '17 at 0:37















    up vote
    95
    down vote



    accepted










    User.FindFirst(ClaimTypes.NameIdentifier).Value


    EDIT for constructor



    Below code works:



    public Controller(IHttpContextAccessor httpContextAccessor)
    {
    var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
    }


    Edit for RTM



    You should register IHttpContextAccessor:



        public void ConfigureServices(IServiceCollection services)
    {
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }





    share|improve this answer



















    • 1




      it works in actions.but i wanna use in constructor of controller.
      – Mehran Hafizi
      Apr 15 '16 at 8:31






    • 1




      is it possible use this in classes?
      – Mehran Hafizi
      Apr 15 '16 at 8:53






    • 1




      because of dependency injection, yes you can use
      – adem caglin
      Apr 15 '16 at 8:55






    • 1




      ClaimTypes.NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.
      – Nikolay Kostov
      Mar 7 '17 at 16:16










    • Does this work for Web Api as well as MVC?
      – Jin Izzraeel
      Dec 9 '17 at 0:37













    up vote
    95
    down vote



    accepted







    up vote
    95
    down vote



    accepted






    User.FindFirst(ClaimTypes.NameIdentifier).Value


    EDIT for constructor



    Below code works:



    public Controller(IHttpContextAccessor httpContextAccessor)
    {
    var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
    }


    Edit for RTM



    You should register IHttpContextAccessor:



        public void ConfigureServices(IServiceCollection services)
    {
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }





    share|improve this answer














    User.FindFirst(ClaimTypes.NameIdentifier).Value


    EDIT for constructor



    Below code works:



    public Controller(IHttpContextAccessor httpContextAccessor)
    {
    var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
    }


    Edit for RTM



    You should register IHttpContextAccessor:



        public void ConfigureServices(IServiceCollection services)
    {
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Aug 14 '16 at 14:44

























    answered Apr 15 '16 at 8:22









    adem caglin

    9,92542849




    9,92542849








    • 1




      it works in actions.but i wanna use in constructor of controller.
      – Mehran Hafizi
      Apr 15 '16 at 8:31






    • 1




      is it possible use this in classes?
      – Mehran Hafizi
      Apr 15 '16 at 8:53






    • 1




      because of dependency injection, yes you can use
      – adem caglin
      Apr 15 '16 at 8:55






    • 1




      ClaimTypes.NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.
      – Nikolay Kostov
      Mar 7 '17 at 16:16










    • Does this work for Web Api as well as MVC?
      – Jin Izzraeel
      Dec 9 '17 at 0:37














    • 1




      it works in actions.but i wanna use in constructor of controller.
      – Mehran Hafizi
      Apr 15 '16 at 8:31






    • 1




      is it possible use this in classes?
      – Mehran Hafizi
      Apr 15 '16 at 8:53






    • 1




      because of dependency injection, yes you can use
      – adem caglin
      Apr 15 '16 at 8:55






    • 1




      ClaimTypes.NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.
      – Nikolay Kostov
      Mar 7 '17 at 16:16










    • Does this work for Web Api as well as MVC?
      – Jin Izzraeel
      Dec 9 '17 at 0:37








    1




    1




    it works in actions.but i wanna use in constructor of controller.
    – Mehran Hafizi
    Apr 15 '16 at 8:31




    it works in actions.but i wanna use in constructor of controller.
    – Mehran Hafizi
    Apr 15 '16 at 8:31




    1




    1




    is it possible use this in classes?
    – Mehran Hafizi
    Apr 15 '16 at 8:53




    is it possible use this in classes?
    – Mehran Hafizi
    Apr 15 '16 at 8:53




    1




    1




    because of dependency injection, yes you can use
    – adem caglin
    Apr 15 '16 at 8:55




    because of dependency injection, yes you can use
    – adem caglin
    Apr 15 '16 at 8:55




    1




    1




    ClaimTypes.NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.
    – Nikolay Kostov
    Mar 7 '17 at 16:16




    ClaimTypes.NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.
    – Nikolay Kostov
    Mar 7 '17 at 16:16












    Does this work for Web Api as well as MVC?
    – Jin Izzraeel
    Dec 9 '17 at 0:37




    Does this work for Web Api as well as MVC?
    – Jin Izzraeel
    Dec 9 '17 at 0:37












    up vote
    26
    down vote













    Simple way that works and I checked.



    var user = await _userManager.GetUserAsync(HttpContext.User);


    then you can all the properties of this variables like user.Email. I hope this would help someone.






    share|improve this answer





















    • works great for me inside a controller in asp.net Core 2.0
      – jmdon
      Mar 26 at 16:59






    • 1




      what is a _userManager?
      – NullVoxPopuli
      Jul 20 at 12:23






    • 1




      In ASP.NET Core Identity, User Manager is a service provided by Dependency Inject to Create Users. See docs for more info:
      – Ahmad
      Jul 20 at 14:25

















    up vote
    26
    down vote













    Simple way that works and I checked.



    var user = await _userManager.GetUserAsync(HttpContext.User);


    then you can all the properties of this variables like user.Email. I hope this would help someone.






    share|improve this answer





















    • works great for me inside a controller in asp.net Core 2.0
      – jmdon
      Mar 26 at 16:59






    • 1




      what is a _userManager?
      – NullVoxPopuli
      Jul 20 at 12:23






    • 1




      In ASP.NET Core Identity, User Manager is a service provided by Dependency Inject to Create Users. See docs for more info:
      – Ahmad
      Jul 20 at 14:25















    up vote
    26
    down vote










    up vote
    26
    down vote









    Simple way that works and I checked.



    var user = await _userManager.GetUserAsync(HttpContext.User);


    then you can all the properties of this variables like user.Email. I hope this would help someone.






    share|improve this answer












    Simple way that works and I checked.



    var user = await _userManager.GetUserAsync(HttpContext.User);


    then you can all the properties of this variables like user.Email. I hope this would help someone.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Feb 27 '17 at 18:24









    Ahmad

    96411323




    96411323












    • works great for me inside a controller in asp.net Core 2.0
      – jmdon
      Mar 26 at 16:59






    • 1




      what is a _userManager?
      – NullVoxPopuli
      Jul 20 at 12:23






    • 1




      In ASP.NET Core Identity, User Manager is a service provided by Dependency Inject to Create Users. See docs for more info:
      – Ahmad
      Jul 20 at 14:25




















    • works great for me inside a controller in asp.net Core 2.0
      – jmdon
      Mar 26 at 16:59






    • 1




      what is a _userManager?
      – NullVoxPopuli
      Jul 20 at 12:23






    • 1




      In ASP.NET Core Identity, User Manager is a service provided by Dependency Inject to Create Users. See docs for more info:
      – Ahmad
      Jul 20 at 14:25


















    works great for me inside a controller in asp.net Core 2.0
    – jmdon
    Mar 26 at 16:59




    works great for me inside a controller in asp.net Core 2.0
    – jmdon
    Mar 26 at 16:59




    1




    1




    what is a _userManager?
    – NullVoxPopuli
    Jul 20 at 12:23




    what is a _userManager?
    – NullVoxPopuli
    Jul 20 at 12:23




    1




    1




    In ASP.NET Core Identity, User Manager is a service provided by Dependency Inject to Create Users. See docs for more info:
    – Ahmad
    Jul 20 at 14:25






    In ASP.NET Core Identity, User Manager is a service provided by Dependency Inject to Create Users. See docs for more info:
    – Ahmad
    Jul 20 at 14:25












    up vote
    18
    down vote













    Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^



    // Stores UserManager
    private readonly UserManager<ApplicationUser> _manager;

    // Inject UserManager using dependency injection.
    // Works only if you choose "Individual user accounts" during project creation.
    public DemoController(UserManager<ApplicationUser> manager)
    {
    _manager = manager;
    }

    // You can also just take part after return and use it in async methods.
    private async Task<ApplicationUser> GetCurrentUser()
    {
    return await _manager.GetUserAsync(HttpContext.User);
    }

    // Generic demo method.
    public async Task DemoMethod()
    {
    var user = await GetCurrentUser();
    string userEmail = user.Email; // Here you gets user email
    string userId = user.Id;
    }


    That code goes to controller named DemoController. Won't work without both await (won't compile) ;)






    share|improve this answer























    • This requires the use of Identity
      – Fraze
      Sep 27 at 17:43










    • What is ApplicationUser?
      – Mike
      Dec 13 at 15:47















    up vote
    18
    down vote













    Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^



    // Stores UserManager
    private readonly UserManager<ApplicationUser> _manager;

    // Inject UserManager using dependency injection.
    // Works only if you choose "Individual user accounts" during project creation.
    public DemoController(UserManager<ApplicationUser> manager)
    {
    _manager = manager;
    }

    // You can also just take part after return and use it in async methods.
    private async Task<ApplicationUser> GetCurrentUser()
    {
    return await _manager.GetUserAsync(HttpContext.User);
    }

    // Generic demo method.
    public async Task DemoMethod()
    {
    var user = await GetCurrentUser();
    string userEmail = user.Email; // Here you gets user email
    string userId = user.Id;
    }


    That code goes to controller named DemoController. Won't work without both await (won't compile) ;)






    share|improve this answer























    • This requires the use of Identity
      – Fraze
      Sep 27 at 17:43










    • What is ApplicationUser?
      – Mike
      Dec 13 at 15:47













    up vote
    18
    down vote










    up vote
    18
    down vote









    Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^



    // Stores UserManager
    private readonly UserManager<ApplicationUser> _manager;

    // Inject UserManager using dependency injection.
    // Works only if you choose "Individual user accounts" during project creation.
    public DemoController(UserManager<ApplicationUser> manager)
    {
    _manager = manager;
    }

    // You can also just take part after return and use it in async methods.
    private async Task<ApplicationUser> GetCurrentUser()
    {
    return await _manager.GetUserAsync(HttpContext.User);
    }

    // Generic demo method.
    public async Task DemoMethod()
    {
    var user = await GetCurrentUser();
    string userEmail = user.Email; // Here you gets user email
    string userId = user.Id;
    }


    That code goes to controller named DemoController. Won't work without both await (won't compile) ;)






    share|improve this answer














    Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^



    // Stores UserManager
    private readonly UserManager<ApplicationUser> _manager;

    // Inject UserManager using dependency injection.
    // Works only if you choose "Individual user accounts" during project creation.
    public DemoController(UserManager<ApplicationUser> manager)
    {
    _manager = manager;
    }

    // You can also just take part after return and use it in async methods.
    private async Task<ApplicationUser> GetCurrentUser()
    {
    return await _manager.GetUserAsync(HttpContext.User);
    }

    // Generic demo method.
    public async Task DemoMethod()
    {
    var user = await GetCurrentUser();
    string userEmail = user.Email; // Here you gets user email
    string userId = user.Id;
    }


    That code goes to controller named DemoController. Won't work without both await (won't compile) ;)







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Sep 9 at 20:39









    Jay Jay Jay

    9401539




    9401539










    answered Aug 17 '16 at 13:00









    Hekkaryk

    357212




    357212












    • This requires the use of Identity
      – Fraze
      Sep 27 at 17:43










    • What is ApplicationUser?
      – Mike
      Dec 13 at 15:47


















    • This requires the use of Identity
      – Fraze
      Sep 27 at 17:43










    • What is ApplicationUser?
      – Mike
      Dec 13 at 15:47
















    This requires the use of Identity
    – Fraze
    Sep 27 at 17:43




    This requires the use of Identity
    – Fraze
    Sep 27 at 17:43












    What is ApplicationUser?
    – Mike
    Dec 13 at 15:47




    What is ApplicationUser?
    – Mike
    Dec 13 at 15:47










    up vote
    11
    down vote













    It would appear that as of now (April of 2017) that the following works:



    public string LoggedInUser => User.Identity;


    At least while within a Controller






    share|improve this answer

















    • 3




      You cannot implicitly convert type 'System.Security.Principal.IIdentity' to 'string'.
      – Anthony Huang
      Mar 15 at 19:21






    • 1




      string LoggedInUser = User.Identity.Name;
      – Alic W
      Sep 1 at 3:27






    • 1




      As someone who hadn't seen the => operator used like this before, it is called an "Expression Body Definition" and is described in this documentation. Just in case future people like me are wondering.
      – Nathan Clement
      Oct 22 at 16:46















    up vote
    11
    down vote













    It would appear that as of now (April of 2017) that the following works:



    public string LoggedInUser => User.Identity;


    At least while within a Controller






    share|improve this answer

















    • 3




      You cannot implicitly convert type 'System.Security.Principal.IIdentity' to 'string'.
      – Anthony Huang
      Mar 15 at 19:21






    • 1




      string LoggedInUser = User.Identity.Name;
      – Alic W
      Sep 1 at 3:27






    • 1




      As someone who hadn't seen the => operator used like this before, it is called an "Expression Body Definition" and is described in this documentation. Just in case future people like me are wondering.
      – Nathan Clement
      Oct 22 at 16:46













    up vote
    11
    down vote










    up vote
    11
    down vote









    It would appear that as of now (April of 2017) that the following works:



    public string LoggedInUser => User.Identity;


    At least while within a Controller






    share|improve this answer












    It would appear that as of now (April of 2017) that the following works:



    public string LoggedInUser => User.Identity;


    At least while within a Controller







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Apr 18 '17 at 15:10









    Grandizer

    1,26112750




    1,26112750








    • 3




      You cannot implicitly convert type 'System.Security.Principal.IIdentity' to 'string'.
      – Anthony Huang
      Mar 15 at 19:21






    • 1




      string LoggedInUser = User.Identity.Name;
      – Alic W
      Sep 1 at 3:27






    • 1




      As someone who hadn't seen the => operator used like this before, it is called an "Expression Body Definition" and is described in this documentation. Just in case future people like me are wondering.
      – Nathan Clement
      Oct 22 at 16:46














    • 3




      You cannot implicitly convert type 'System.Security.Principal.IIdentity' to 'string'.
      – Anthony Huang
      Mar 15 at 19:21






    • 1




      string LoggedInUser = User.Identity.Name;
      – Alic W
      Sep 1 at 3:27






    • 1




      As someone who hadn't seen the => operator used like this before, it is called an "Expression Body Definition" and is described in this documentation. Just in case future people like me are wondering.
      – Nathan Clement
      Oct 22 at 16:46








    3




    3




    You cannot implicitly convert type 'System.Security.Principal.IIdentity' to 'string'.
    – Anthony Huang
    Mar 15 at 19:21




    You cannot implicitly convert type 'System.Security.Principal.IIdentity' to 'string'.
    – Anthony Huang
    Mar 15 at 19:21




    1




    1




    string LoggedInUser = User.Identity.Name;
    – Alic W
    Sep 1 at 3:27




    string LoggedInUser = User.Identity.Name;
    – Alic W
    Sep 1 at 3:27




    1




    1




    As someone who hadn't seen the => operator used like this before, it is called an "Expression Body Definition" and is described in this documentation. Just in case future people like me are wondering.
    – Nathan Clement
    Oct 22 at 16:46




    As someone who hadn't seen the => operator used like this before, it is called an "Expression Body Definition" and is described in this documentation. Just in case future people like me are wondering.
    – Nathan Clement
    Oct 22 at 16:46










    up vote
    3
    down vote













    My problem was to access the logged in User as an object in the cshtml file. Considering you wanted the user in ViewData, this approach might be helpful:



    In the cshtml file



    @using Microsoft.AspNetCore.Identity
    @inject UserManager<ApplicationUser> UserManager

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>
    @UserManager.FindByNameAsync(UserManager.GetUserName(User)).Result.Email
    </title>
    </head>
    <body>

    </body>
    </html>





    share|improve this answer





















    • Any idea how you might get a navigation property to load (Company name of a company navigation property on my ApplicationUser class). Didn't see a way to include navigation properties.
      – Hunter Nelson
      Oct 2 at 5:39















    up vote
    3
    down vote













    My problem was to access the logged in User as an object in the cshtml file. Considering you wanted the user in ViewData, this approach might be helpful:



    In the cshtml file



    @using Microsoft.AspNetCore.Identity
    @inject UserManager<ApplicationUser> UserManager

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>
    @UserManager.FindByNameAsync(UserManager.GetUserName(User)).Result.Email
    </title>
    </head>
    <body>

    </body>
    </html>





    share|improve this answer





















    • Any idea how you might get a navigation property to load (Company name of a company navigation property on my ApplicationUser class). Didn't see a way to include navigation properties.
      – Hunter Nelson
      Oct 2 at 5:39













    up vote
    3
    down vote










    up vote
    3
    down vote









    My problem was to access the logged in User as an object in the cshtml file. Considering you wanted the user in ViewData, this approach might be helpful:



    In the cshtml file



    @using Microsoft.AspNetCore.Identity
    @inject UserManager<ApplicationUser> UserManager

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>
    @UserManager.FindByNameAsync(UserManager.GetUserName(User)).Result.Email
    </title>
    </head>
    <body>

    </body>
    </html>





    share|improve this answer












    My problem was to access the logged in User as an object in the cshtml file. Considering you wanted the user in ViewData, this approach might be helpful:



    In the cshtml file



    @using Microsoft.AspNetCore.Identity
    @inject UserManager<ApplicationUser> UserManager

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>
    @UserManager.FindByNameAsync(UserManager.GetUserName(User)).Result.Email
    </title>
    </head>
    <body>

    </body>
    </html>






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered May 2 at 12:52









    MikeMajara

    10919




    10919












    • Any idea how you might get a navigation property to load (Company name of a company navigation property on my ApplicationUser class). Didn't see a way to include navigation properties.
      – Hunter Nelson
      Oct 2 at 5:39


















    • Any idea how you might get a navigation property to load (Company name of a company navigation property on my ApplicationUser class). Didn't see a way to include navigation properties.
      – Hunter Nelson
      Oct 2 at 5:39
















    Any idea how you might get a navigation property to load (Company name of a company navigation property on my ApplicationUser class). Didn't see a way to include navigation properties.
    – Hunter Nelson
    Oct 2 at 5:39




    Any idea how you might get a navigation property to load (Company name of a company navigation property on my ApplicationUser class). Didn't see a way to include navigation properties.
    – Hunter Nelson
    Oct 2 at 5:39










    up vote
    1
    down vote













    In addition to existing answers I'd like to add that you can also have a class instance available app-wide which holds user-related data like UserID etc.



    It may be useful for refactoring e.g. you don't want to fetch UserID in every controller action and declare an extra UserID parameter in every method related to Service Layer.



    I've done a research and here's my post.



    You just extend your class which you derive from DbContext by adding UserId property (or implement a custom Session class which has this property).



    At filter level you can fetch your class instance and set UserId value.



    After that wherever you inject your instance - it will have the necessary data (lifetime must be per request, so you register it using AddScoped method).



    Working example:



    public class AppInitializationFilter : IAsyncActionFilter
    {
    private DBContextWithUserAuditing _dbContext;

    public AppInitializationFilter(
    DBContextWithUserAuditing dbContext
    )
    {
    _dbContext = dbContext;
    }

    public async Task OnActionExecutionAsync(
    ActionExecutingContext context,
    ActionExecutionDelegate next
    )
    {
    string userId = null;
    int? tenantId = null;

    var claimsIdentity = (ClaimsIdentity)context.HttpContext.User.Identity;

    var userIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
    if (userIdClaim != null)
    {
    userId = userIdClaim.Value;
    }

    var tenantIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == CustomClaims.TenantId);
    if (tenantIdClaim != null)
    {
    tenantId = !string.IsNullOrEmpty(tenantIdClaim.Value) ? int.Parse(tenantIdClaim.Value) : (int?)null;
    }

    _dbContext.UserId = userId;
    _dbContext.TenantId = tenantId;

    var resultContext = await next();
    }
    }


    For more information see my answer.






    share|improve this answer



























      up vote
      1
      down vote













      In addition to existing answers I'd like to add that you can also have a class instance available app-wide which holds user-related data like UserID etc.



      It may be useful for refactoring e.g. you don't want to fetch UserID in every controller action and declare an extra UserID parameter in every method related to Service Layer.



      I've done a research and here's my post.



      You just extend your class which you derive from DbContext by adding UserId property (or implement a custom Session class which has this property).



      At filter level you can fetch your class instance and set UserId value.



      After that wherever you inject your instance - it will have the necessary data (lifetime must be per request, so you register it using AddScoped method).



      Working example:



      public class AppInitializationFilter : IAsyncActionFilter
      {
      private DBContextWithUserAuditing _dbContext;

      public AppInitializationFilter(
      DBContextWithUserAuditing dbContext
      )
      {
      _dbContext = dbContext;
      }

      public async Task OnActionExecutionAsync(
      ActionExecutingContext context,
      ActionExecutionDelegate next
      )
      {
      string userId = null;
      int? tenantId = null;

      var claimsIdentity = (ClaimsIdentity)context.HttpContext.User.Identity;

      var userIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
      if (userIdClaim != null)
      {
      userId = userIdClaim.Value;
      }

      var tenantIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == CustomClaims.TenantId);
      if (tenantIdClaim != null)
      {
      tenantId = !string.IsNullOrEmpty(tenantIdClaim.Value) ? int.Parse(tenantIdClaim.Value) : (int?)null;
      }

      _dbContext.UserId = userId;
      _dbContext.TenantId = tenantId;

      var resultContext = await next();
      }
      }


      For more information see my answer.






      share|improve this answer

























        up vote
        1
        down vote










        up vote
        1
        down vote









        In addition to existing answers I'd like to add that you can also have a class instance available app-wide which holds user-related data like UserID etc.



        It may be useful for refactoring e.g. you don't want to fetch UserID in every controller action and declare an extra UserID parameter in every method related to Service Layer.



        I've done a research and here's my post.



        You just extend your class which you derive from DbContext by adding UserId property (or implement a custom Session class which has this property).



        At filter level you can fetch your class instance and set UserId value.



        After that wherever you inject your instance - it will have the necessary data (lifetime must be per request, so you register it using AddScoped method).



        Working example:



        public class AppInitializationFilter : IAsyncActionFilter
        {
        private DBContextWithUserAuditing _dbContext;

        public AppInitializationFilter(
        DBContextWithUserAuditing dbContext
        )
        {
        _dbContext = dbContext;
        }

        public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next
        )
        {
        string userId = null;
        int? tenantId = null;

        var claimsIdentity = (ClaimsIdentity)context.HttpContext.User.Identity;

        var userIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
        if (userIdClaim != null)
        {
        userId = userIdClaim.Value;
        }

        var tenantIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == CustomClaims.TenantId);
        if (tenantIdClaim != null)
        {
        tenantId = !string.IsNullOrEmpty(tenantIdClaim.Value) ? int.Parse(tenantIdClaim.Value) : (int?)null;
        }

        _dbContext.UserId = userId;
        _dbContext.TenantId = tenantId;

        var resultContext = await next();
        }
        }


        For more information see my answer.






        share|improve this answer














        In addition to existing answers I'd like to add that you can also have a class instance available app-wide which holds user-related data like UserID etc.



        It may be useful for refactoring e.g. you don't want to fetch UserID in every controller action and declare an extra UserID parameter in every method related to Service Layer.



        I've done a research and here's my post.



        You just extend your class which you derive from DbContext by adding UserId property (or implement a custom Session class which has this property).



        At filter level you can fetch your class instance and set UserId value.



        After that wherever you inject your instance - it will have the necessary data (lifetime must be per request, so you register it using AddScoped method).



        Working example:



        public class AppInitializationFilter : IAsyncActionFilter
        {
        private DBContextWithUserAuditing _dbContext;

        public AppInitializationFilter(
        DBContextWithUserAuditing dbContext
        )
        {
        _dbContext = dbContext;
        }

        public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next
        )
        {
        string userId = null;
        int? tenantId = null;

        var claimsIdentity = (ClaimsIdentity)context.HttpContext.User.Identity;

        var userIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
        if (userIdClaim != null)
        {
        userId = userIdClaim.Value;
        }

        var tenantIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == CustomClaims.TenantId);
        if (tenantIdClaim != null)
        {
        tenantId = !string.IsNullOrEmpty(tenantIdClaim.Value) ? int.Parse(tenantIdClaim.Value) : (int?)null;
        }

        _dbContext.UserId = userId;
        _dbContext.TenantId = tenantId;

        var resultContext = await next();
        }
        }


        For more information see my answer.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Oct 20 at 8:48

























        answered Oct 20 at 7:25









        Alex Herman

        603614




        603614






















            up vote
            -1
            down vote













            I got my solution



            var claim = HttpContext.User.CurrentUserID();

            public static class XYZ
            {
            public static int CurrentUserID(this ClaimsPrincipal claim)
            {
            var userID = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
            "UserID").Value;
            return Convert.ToInt32(userID);
            }
            public static string CurrentUserRole(this ClaimsPrincipal claim)
            {
            var role = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
            "Role").Value;
            return role;
            }
            }





            share|improve this answer





















            • While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
              – Alexander
              May 10 at 17:04















            up vote
            -1
            down vote













            I got my solution



            var claim = HttpContext.User.CurrentUserID();

            public static class XYZ
            {
            public static int CurrentUserID(this ClaimsPrincipal claim)
            {
            var userID = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
            "UserID").Value;
            return Convert.ToInt32(userID);
            }
            public static string CurrentUserRole(this ClaimsPrincipal claim)
            {
            var role = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
            "Role").Value;
            return role;
            }
            }





            share|improve this answer





















            • While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
              – Alexander
              May 10 at 17:04













            up vote
            -1
            down vote










            up vote
            -1
            down vote









            I got my solution



            var claim = HttpContext.User.CurrentUserID();

            public static class XYZ
            {
            public static int CurrentUserID(this ClaimsPrincipal claim)
            {
            var userID = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
            "UserID").Value;
            return Convert.ToInt32(userID);
            }
            public static string CurrentUserRole(this ClaimsPrincipal claim)
            {
            var role = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
            "Role").Value;
            return role;
            }
            }





            share|improve this answer












            I got my solution



            var claim = HttpContext.User.CurrentUserID();

            public static class XYZ
            {
            public static int CurrentUserID(this ClaimsPrincipal claim)
            {
            var userID = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
            "UserID").Value;
            return Convert.ToInt32(userID);
            }
            public static string CurrentUserRole(this ClaimsPrincipal claim)
            {
            var role = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
            "Role").Value;
            return role;
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 10 at 16:55









            neeraj rai

            1




            1












            • While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
              – Alexander
              May 10 at 17:04


















            • While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
              – Alexander
              May 10 at 17:04
















            While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
            – Alexander
            May 10 at 17:04




            While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
            – Alexander
            May 10 at 17:04


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36641338%2fhow-get-current-user-in-asp-net-core%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            Origin of the phrase “under your belt”?