在Action Filter中获取UserID(不是Identity.Name)

问题描述:

我需要在ASP.Net MVC应用程序的Action Filter中找到UserID。我可以在一个正常的控制器中得到相同的结果,如下所示。在Action Filter中获取UserID(不是Identity.Name)

enter image description here

我知道如何在操作过滤器获得用户名。

enter image description here

但是,当我试图让用户ID,我得到错误

string userID = filterContext.HttpContext.User.Identity.GetUserID(); 

错误CS1061 '的IIdentity' 不包含一个定义为 'GetUserID',没有扩展方法 'GetUserID'接受类型'IIdentity'的第一个参数可能被发现

如何获取用户ID在动作过滤器?

更新 - 参考:

  1. ClaimsIdentityExtensions

规范行为过滤

using System; 
using System.Collections.Generic;////Not used 
using System.Linq;////Not used 
using System.Web;////Not used 
using System.Web.Mvc; 
using System.Web.Routing; 
using Microsoft.AspNet.Identity; ////Not used 

namespace MyPortal 
{ 
    public class ActionFilterSessionCheck : ActionFilterAttribute, IActionFilter 
    { 
     void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      string userName = null; 
      if (filterContext.HttpContext.User.Identity.IsAuthenticated) 
      { 
       userName = filterContext.HttpContext.User.Identity.Name; 

       //ERROR*** 
       //string userID = filterContext.HttpContext.User.Identity.GetUserID(); 

      } 

      string sessionLogin = "Login" + userName; 
      if (userName == null || (System.Web.HttpContext.Current.Session[sessionLogin] == null)) 
      { 

       if (filterContext.HttpContext.Request.IsAjaxRequest()) 
       { 
        //AJAX request 
        throw new Exception("Session time out"); 
       } 
       else 
       { 
        // Standard request 
        filterContext.Result = new RedirectToRouteResult(
             new RouteValueDictionary 
             { 
             { "action", "Login" }, 
             { "controller", "Account" } 
             }); 
       } 
      } 


      //Call standard behavior 
      this.OnActionExecuting(filterContext); 
     } 
    } 

} 
+0

即使在过滤器中添加代码也会出错,如果您需要id,则需要通过名称手动检查名称 –

你需要的功能是GetUserId,不GetUserID。它被定义为here

您的工作示例与您的错误之间的区别仅仅是您错误地使用了ID而不是Id