This method makes use of an Action Filter Attribute class to handle action execution on controllers. Firstly you need to create a new Action Filter class, calling it anything you want, but make it inherit from the ActionFilterAttribute class. You should then add the overrided OnActionExecuted method with the ActionExecutedContext argument:
public class ExampleActonFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
BaseViewModel model = filtercontext.Controller.ViewData.Model;
if (filterContext.Controller.ControllerContext.HttpContext.Session["UserName"] != null)
{
model.UserName = filterContext.Controller.ControllerContext.HttpContext.Session["UserName"];
}
}
}
Next, you have your layout page take a ViewModel with a public string parameter taking the username as a string:
public class BaseViewModel()
{
public string UserName {get;set;}
}
Then on your layout page have a simple check (where you would like it to be drawn) to make sure that value is not null and if it isn't, to draw it like so:
if (string.IsNullOrWhiteSpace(@Model.UserName))
{
<span>@Model.UserName</span>
}
Now in all of your views where you want to show the user name, simply have your ViewModel for that page inherit from your BaseViewModel class and set the username to the session variable when you want it to be shown.
Have a look at this SO post for more information about session variables: here
I hope this helps!