ASP.NET MVC在自定义操作筛选器中查找当前用户名

twa*_*ron 18 asp.net-mvc action-filter

我正在为asp.net MVC创建一个自定义动作过滤器.

OnActionExecuting()方法中.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    string userName =  ?????// how can I get this?
}   
Run Code Online (Sandbox Code Playgroud)

我需要找出当前的用户名(我正在使用表单身份验证)

在控制器中我可以简单地做 User.Identity.Name

有没有办法在ActionFilter中获取用户名?

Dar*_*rov 42

string userName = filterContext.HttpContext.User.Identity.Name;
Run Code Online (Sandbox Code Playgroud)

如果您想先检查是否有经过身份验证的用户:

string userName = null;
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
    userName = filterContext.HttpContext.User.Identity.Name;
}
Run Code Online (Sandbox Code Playgroud)