When accessing the current user in my Windows authenticated .net core mvc app, User.Identity.Name returns Domain\Username. I am trying to implement a custom base controller so that I can change the User.Identity.Name to just Username and save it to a field for every controller that extends my base controller. I created an abstract class BaseController but when I try to access User.Identity.Name I get a null reference exception. I also tried Dependency Injection to use the HttpContextAccessor but then every controller that extends my BaseController gets an error. Here are the examples of what I tried:
public abstract class BaseController : Controller
{
public readonly username;
public BaseController()
{
username = User.Identity.Name.Split("\\")[1]; // Null reference exception
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}
public abstract class BaseController : Controller
{
public readonly username;
public BaseController(IHttpContextAccessor httpContextAccessor)
{
username =httpContextAccessor.HttpContext.User.Identity.Name.Split("\\")[1];
}
}
public HomeController : BaseController // Won't compile
{
public IActionResult Index()
{
ViewData["CurrentUser"] = username;
return View();
}
}
How can I do this?