【问题标题】:ASP.NET MVC finding the current username in a custom action filterASP.NET MVC 在自定义操作过滤器中查找当前用户名
【发布时间】:2011-10-19 17:01:09
【问题描述】:

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

OnActionExecuting() 方法中。

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

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

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

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

【问题讨论】:

    标签: asp.net-mvc action-filter


    【解决方案1】:
    string userName = filterContext.HttpContext.User.Identity.Name;
    

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

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

    【讨论】:

    • 嗯,这非常容易,不知道为什么我很难找到它。再次感谢达林!
    • @DarinDimitrov 如何获取 UserId 而不是名称?在控制器操作中,我可以简单地使用User.Identity.GetUserId();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多