Question

I use MVC4 web application with Web API. I want to create an action filter, and I want to know which user (a logged-in user) made the action. How can I do it?

public class ModelActionLog : ActionFilterAttribute
{
    public override void OnActionExecuting(SHttpActionContext actionContext)
    {
       string username = ??
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       ??
    }
}
Was it helpful?

Solution 2

You can try

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
           string username = HttpContext.Current.User.Identity.Name;
        }

Check for authenticated user first:

string userName = null;
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
    userName = HttpContext.Current.User.Identity.Name;
}

Try to use

HttpContext.Current.User.Identity.Name

Hope it works for you

OTHER TIPS

Bit late for an answer but this is best solution if you are using HttpActionContext in your filter You can always use it as mentioned here:-

public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
   if (actionContext.RequestContext.Principal.Identity.IsAuthenticated)
   {
      var userName = actionContext.RequestContext.Principal.Identity.Name;
   }
}

Perhaps not the prettiest solution, but for Web API ActionFilter you can do the following:

var controller = (actionContext.ControllerContext.Controller as ApiController);
var principal = controller.User;

Of course, this only applies if your controllers actually inherit from ApiController.

This is what you need

string username = filterContext.HttpContext.User.Identity.Name;
 HttpContext.Current.User.Identity.Name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top