문제

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)
    {
       ??
    }
}
도움이 되었습니까?

해결책 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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top