C# 4.0 在我的基本控制器构造函数上获取用户标识
我的ASP.NET MVC4网站上有一个基本控制器,其构造函数如下所示:C# 4.0 在我的基本控制器构造函数上获取用户标识,c#-4.0,asp.net-mvc-4,asp.net-membership,.net-4.5,C# 4.0,Asp.net Mvc 4,Asp.net Membership,.net 4.5,我的ASP.NET MVC4网站上有一个基本控制器,其构造函数如下所示: public class BaseController : Controller { protected MyClass Foo { get; set; } public BaseController() { if (User.Identity.IsAuthenticated)) { Foo = new MyClass(); }
public class BaseController : Controller
{
protected MyClass Foo { get; set; }
public BaseController()
{
if (User.Identity.IsAuthenticated))
{
Foo = new MyClass();
}
}
}
但是,我无法在此访问User
。它是null
。但是在我继承的控制器上很好
谢谢控制器实例化将在授权发生之前进行。即使您的MVC应用程序多次调用
RenderAction()
,并且最终创建了五个不同的控制器,这五个控制器也将在任何情况发生之前创建
处理这些情况的最佳方法是使用。该软件很早就被解雇了,很可能适合您的情况
首先,让我们创建一个授权过滤器
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyClassAuthorizationAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.ViewData["MyClassInstance"] = new MyClass();
}
}
}
现在,让我们更新我们的控制器
[MyClassAuthorization]
public class BaseController : Controller
{
protected MyClass Foo
{
get { return (MyClass)ViewData["MyClassInstance"]; }
}
}
在这种情况下,我将:
使用System.Web.HttpContext.Current.User而不是User
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
// User.Identity is accessible here
}