Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get User Name on Action Filter

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)
    {
       ??
    }
}
like image 243
TamarG Avatar asked May 20 '13 12:05

TamarG


People also ask

How do I redirect an action filter?

Alternatively to a redirect, if it is calling your own code, you could use this: actionContext. Result = new RedirectToRouteResult( new RouteValueDictionary(new { controller = "Home", action = "Error" }) ); actionContext. Result.

How do I use action filter in Web API?

Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns. Result filters contain logic that is executed before and after a view result is executed.

What is action filter attribute?

Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which an action is executed.


3 Answers

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;
   }
}
like image 57
Atul Chaudhary Avatar answered Oct 15 '22 19:10

Atul Chaudhary


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

like image 46
Rahul Avatar answered Oct 15 '22 17:10

Rahul


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.

like image 4
Morten Christiansen Avatar answered Oct 15 '22 19:10

Morten Christiansen