Get current login user id from Active Directory in ASP.Net using AngularJS

Amol111
 
on Jun 01, 2022 08:08 AM
596 Views

How to get / read the current user login id from active directory in AngularJS.

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jun 02, 2022 01:00 AM
on Jun 02, 2022 02:29 AM

Hi Amol111,

On order to get the current user login user, you need to make ajax call and fetch the logged in user details.

Refer below example.

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', [])
    app.controller('MyController', function ($scope, $http, $window) {
        $scope.ButtonClick = function () {
            var post = $http({
                method: "POST",
                url: "Default.aspx/GetUserName",
                dataType: 'json',
                data: {},
                headers: { "Content-Type": "application/json" }
            });

            post.success(function (data, status) {
                $window.alert("Logged in User\n" + data.d);
            });

            post.error(function (data, status) {
                $window.alert(data.Message);
            });
        }
    });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <input type="button" value="Submit" ng-click="ButtonClick()" />
</div>

Code

C#

[System.Web.Services.WebMethod]
public static string GetUserName()
{
    string name = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;
    return name;
}

VB.Net

<System.Web.Services.WebMethod>
Public Shared Function GetUserName() As String
    Dim name As String = New System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name
    Return name
End Function

Screenshot