I need to find UserID
in an Action Filter of an ASP.Net MVC application. I can get the same in a normal controller as shown below.
I know how to get UserName in Action Filter.
But when I try to get UserID, I get error
string userID = filterContext.HttpContext.User.Identity.GetUserID();
Error CS1061 'IIdentity' does not contain a definition for 'GetUserID' and no extension method 'GetUserID' accepting a first argument of type 'IIdentity' could be found
How to get UserID inside Action Filter?
Update - REFERENCE:
Code for Action Filter
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);
}
}
}
The function you need is GetUserId
, not GetUserID
. It is defined here.
The difference between your working example and your error is simply that you wrongly use ID
instead of Id
.