The MVC application is developed in .Net Framework 4.7.2. User Name is always null in OnActionExecuting method.
I'm unable to reproduce this problem. The username is populated for all authenticated users. The test code is based on the code sample found in the official documentation.
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Log("OnActionExecuting", filterContext.RouteData);
string? username = filterContext.HttpContext.User.Identity.Name;
Log(username);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Log("OnActionExecuted", filterContext.RouteData);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Log("OnResultExecuting", filterContext.RouteData);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Log("OnResultExecuted", filterContext.RouteData);
}
private void Log(string methodName, RouteData routeData)
{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
private void Log(string? value)
{
Debug.WriteLine($"Username = {value}");
}
}
Implementation
[LogActionFilter]
[Authorize]
public class SecureController : Controller
{
public IActionResult Index()
{
return View();
}
}
Results from the debug screen which shows the username.
Action Filter Log: OnActionExecuting controller:Secure action:Index
Username = ******@email.com
Action Filter Log: OnActionExecuted controller:Secure action:Index
Action Filter Log: OnResultExecuting controller:Secure action:Index
Action Filter Log: OnResultExecuted controller:Secure action:Index
There can be many reasons why the username is null. Can you tell us how security works in the application? Is there any way you can provide a working code example that illustrates this problem?