在Action Filter中获取UserID(不是Identity.Name)
问题描述:
我需要在ASP.Net MVC应用程序的Action Filter中找到UserID
。我可以在一个正常的控制器中得到相同的结果,如下所示。在Action Filter中获取UserID(不是Identity.Name)
我知道如何在操作过滤器获得用户名。
但是,当我试图让用户ID,我得到错误
string userID = filterContext.HttpContext.User.Identity.GetUserID();
错误CS1061 '的IIdentity' 不包含一个定义为 'GetUserID',没有扩展方法 'GetUserID'接受类型'IIdentity'的第一个参数可能被发现
如何获取用户ID在动作过滤器?
更新 - 参考:
规范行为过滤
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);
}
}
}
即使在过滤器中添加代码也会出错,如果您需要id,则需要通过名称手动检查名称 –