ASP.NET Core | HttpContext | Get current windows username

Special Note: If you want ONLY get the currently logged in Windows username (useful for Windows domain networks) all you need is to change the website’s authentication to Windows & calling “User.Identity.Name”. The below example mostly looking at how to implement HttpContext in a project.

Recently we decided to retire our Classic ASP intranet application & opted ASP.NET Core for the upgrade. As a Business, we are totally in to Oracle technologies and hardly had much exposure towards .NET development. With the help of netizens, blogs and forums, we figured out the basics of CRUD operations using ASP.NET Core. However, were totally bowled out while getting currently logged in Windows usernames (domain accounts) for the application. Then we came across this post

Using the above post, we managed to figure out way to “get” the Windows username using HttpContext & realizing the above link (although helped us), was too technical for beginners and decided to make a post that simplifies the instructions further a level. So, here it is.

Please note, I am using 2019 community editions for both Visual Studio and MS SQL Database. If you are using a previous versions of Visual Studio, may not able to open the sample solution provided with this post. A note of caution. We are as fresh as possible with ASP.NET Core development & would appreciate pointing out our mistakes instead lamenting. Thank you.

So let us start creating a new ASP.NET Core project that uses C# (ASP.NET Core Web App (Model-View-Controller)

Give a meaningful name for your solution

Select “Windows Authentication” for your solution (must)

Your project explorer should look like this

Open Startup.cs file and modify “ConfigureServices” method like below

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //Rajesh Added the below
            services.AddHttpContextAccessor();


        }

To keep it clean and simple, we will use a class specific to establish HttpContext.

Add a new class to Models, and let us call it “WindowsUserClass”

Add Microsoft.AspNetCore.Http namespace to the class before adding the below properties initializing the class.

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GetWindowsUserName.Models
{
    public class WindowsUserClass
    {

        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly string _userName;
        public WindowsUserClass(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _userName = httpContextAccessor.HttpContext.User.Identity.Name;
        }

        public string GetUserName()
        {
            return _userName;
        }
    }
}

We will use the Controller construct dependency injection (read it, going to be difficult to understand if you are a beginner like us :) ) to initialize the WindowsUserClass by passing IHttpContextAccessor as a parameter.

HomeController constructor before adding IHttpContextAccessor

After modification

You have to add Microsoft.AspNetCore.Http namespace to the controller also.

Now we should able to call the GetUserName() function from WindowsUserClass from the HomeController! Let us give it a try

We’ll modify the Index view call slightly by passing the “yourusername” string.

We’ll modify “Index” view to show our Windows username now. You can call the view directly referring the GetUserName() function also. That will avoid an additional variable declaration.

return View("Index", windowsUserClass.GetUserName());
@model string
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome @Model</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

Before executing your project, we must change one more existing file!

Open launchSettings.json file and modify the content like below

You must change the windowsAuthentication string value to “true” and anonymousAuthentication to “false”. Save the changes.

You can build the solution and run to debug to check whether the solution is working as per expectations. One of the most important things you MUST understand now, for HttpContext to fetch you the intended results, your website should not be configured for Anonymous authentication. Here is the screen once after you enter the windows username and password when prompted!

You must change the website’s authentication methods prior publishing using IIS. For example

Hope this helps few out there! If the situation permits, I might record a video with instructions soon for the same. Stay tuned folks. For those who cannot open the Visual Studio 2019 solution using their versions of VS, find the page codes below. This way of calling HttpContextAccessor is supported from ASP.NET Core 3.1

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GetWindowsUserName
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //Rajesh Added the below
            services.AddHttpContextAccessor();


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

HomeController.cs

using GetWindowsUserName.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace GetWindowsUserName.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        WindowsUserClass windowsUserClass = null;
        public HomeController(ILogger<HomeController> logger, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;

            windowsUserClass = new WindowsUserClass(httpContextAccessor);
        }

        public IActionResult Index()
        {

            string yourusername = windowsUserClass.GetUserName();

            return View("Index",yourusername);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

WindowsUserClass.cs

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GetWindowsUserName.Models
{
    public class WindowsUserClass
    {

        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly string _userName;
        public WindowsUserClass(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _userName = httpContextAccessor.HttpContext.User.Identity.Name;
        }

        public string GetUserName()
        {
            return _userName;
        }
    }
}

You may download the sample solution from this link.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.