_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.