在动作过滤器上获取用户名

本文关键字:获取 用户 过滤器 | 更新日期: 2023-09-27 18:14:20

我使用带有web API的MVC4 web应用程序。我想创建一个操作过滤器,并且我想知道哪个用户(一个登录用户)执行了该操作。我该怎么做呢?

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

在动作过滤器上获取用户名

回答有点晚了,但这是最好的解决方案,如果你在你的过滤器中使用HttpActionContext,你可以随时使用它,如这里所述:-

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

你可以试试

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

先检查认证用户:

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

尝试使用

HttpContext.Current.User.Identity.Name

希望它对你有用

可能不是最漂亮的解决方案,但对于Web API ActionFilter,您可以执行以下操作:

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

当然,这只适用于当你的控制器实际上继承了ApiController

这就是你需要的

string username = filterContext.HttpContext.User.Identity.Name;
 HttpContext.Current.User.Identity.Name