Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 在我的基本控制器构造函数上获取用户标识_C# 4.0_Asp.net Mvc 4_Asp.net Membership_.net 4.5 - Fatal编程技术网

C# 4.0 在我的基本控制器构造函数上获取用户标识

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(); }

我的ASP.NET MVC4网站上有一个基本控制器,其构造函数如下所示:

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
}