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)
{
??
}
}
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.
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.
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.
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;
}
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With