i am trying to show a list of users of my application "school", when admin logs in then he can view all the users in list but when school principals logins, he should get only users of his school, So i thought to get the current loggedIn userId first and then by that userId i'll get schoolId since userId is foreign key in school table...once i'll get the schoolId i can show the members of that school.
But my problem is how to get the UserID of currently loggedIn. I'm using MVC 1.0 Asp.Net -- "Membership"
if my logic above is wrong then please tell me the alternate good idea, so that principal can see only his users list..
How to get the current logged-in user in an active directory when your ASP.NET MVC application is running on a web server inside the network: // Find currently logged in user UserPrincipal adUser = null; using (HostingEnvironment. Impersonate()) { var userContext = System. Web.
You need to set FormsAuthentication. SetAuthCookie(PrimaryKey, false); when user is loggedIn. Here, PrimaryKey is the key that you can use throughout the session for identification of the user using User.Identity.Name . Also, when user log out of the application, you will call FormsAuthentication.
You can display the name of the current user using the LoginName control. This control displays the user ID of the current logged-in user, whether the user's identity is established with ASP.NET login controls (and implicitly, ASP.NET membership) or with Integrated Windows authentication.
You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);
Based on this question and answer by J. Pablo Fernández you can get the user id of the current user with the following code:
//It will only be a Guid if you are using SQL Server as the DB as oppose to MySQL
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
Here is the MSDN Documentation.
The Simple Solution With the scenario you describe you would only be able to do this by retrieving the User information with the data stored in the HttpContext.Current.Identity. For example, if the HttpContext.Current.Identity.Name is the Username, then you would use that value to retrieve the User data for the principal that should include the UserId you can use to locate the appropriate school.
Alternate Solution You might consider storing the SchoolId in the user's profile so that it is more easily accessible.
The easiest way that I've tried
You have to include Microsoft.AspNet.Identity
using Microsoft.AspNet.Identity;
Then use it like this
var userId = User.Identity.GetUserId().ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With