_Layout.cshtml
<span>Hello @ViewBag.Username!</span>
MyController.cs
public class MyController : Controller
{
public ActionResult Index()
{
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string[] a = User.Identity.Name.Split('\\');
System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();
return View();
}
public ActionResult NextView()
{
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string[] a = User.Identity.Name.Split('\\');
System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();
return View();
}
public ActionResult AnotherView()
{
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string[] a = User.Identity.Name.Split('\\');
System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();
return View();
}
}
How can I put this logic into one place so that I don’t repeat myself? I need the User’s name to be displayed throughout all my layouts.
Override the
OnActionExecutingmethod in the controller and put the code to set the Username there.Then you won’t need to set the
ViewBag.Usernameproperty. Any method in the controller will already have it set. If you need it across multiple controllers, put it into a base Controller class.