13 July 2022

How to Get the Current User in ASP.NET Core

 Create new Controller and add below code:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Dotnet_Core_MVC.Controllers
{
    public class ExpHttpContextAccessorController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor = new HttpContextAccessor();
        public IActionResult Index()
        {
            string userName = _httpContextAccessor.HttpContext.User.Identity.Name;
            ViewBag.userName = userName;
            return View();
        }
    }
}

Go to View and add below code:

 <b>Welcome:@ViewBag.userName</b>

Update ConfigureServices() in Startup.cs as below:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddHttpContextAccessor(); 
        }

No comments:

Post a Comment