相关文章推荐

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)

 public void ConfigureServices(IServiceCollection services)
            services.AddControllersWithViews();
            //Rajesh Added the below
            services.AddHttpContextAccessor();
        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;
<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>

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!

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();
                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?}");
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 });
        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;
		
	
								
		Jun »
	
		

Recent Posts

Deprecated: The PSR-0 Requests_… class names in the Request library are deprecated Oracle workflow builder can’t load (or register) custom control wfnvg20.ocx Windows 11 | Snipping tool “Recording stopped” Hack for a small size USB flash disk Fix for Windows 10, 11 virtual machine slowness on VirtualBox
 
推荐文章