How to get current user who's accessing an ASP.NET application?

前端 未结 8 1210
粉色の甜心
粉色の甜心 2020-11-29 06:24

To get the current logged in user at the system I use this code:

string opl = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
         


        
8条回答
  •  眼角桃花
    2020-11-29 07:16

    Don't look too far.

    If you develop with ASP.NET MVC, you simply have the user as a property of the Controller class. So in case you get lost in some models looking for the current user, try to step back and to get the relevant information in the controller.

    In the controller, just use:

    using Microsoft.AspNet.Identity;
    
      ...
    
      var userId = User.Identity.GetUserId();
      ...
    

    with userId as a string.

提交回复
热议问题