问题描述
我对我的ASP.NET网站MVC4基地控制器具有构造简单:
I have a base Controller on my ASP.NET MVC4 website that have a Constructor simple as this:
public class BaseController : Controller
{
protected MyClass Foo { get; set; }
public BaseController()
{
if (User.Identity.IsAuthenticated))
{
Foo = new MyClass();
}
}
}
不过,我无法访问用户
在这里。这是空
。但在我的继承控制器这很好。
However I cannot access User
here. It's null
. But on my inherited Controllers it's fine.
感谢
推荐答案
控制器实例授权发生之前会发生。即使你的MVC应用程序调用的RenderAction()
几次,那么您最终创建比方说,五个不同的控制器,这五个控制器将之前的任何创建OnAuthorization发生。
Controller instantiation will occur before authorisation takes place. Even if your MVC application calls RenderAction()
several times and you end up creating say, five different controllers, those five controllers will be created before any OnAuthorization takes place.
要处理这些情况,最好的方法是使用。在Authorize属性是早期解雇,很可能是适合您的情况。
The best approach to deal with these situations is to use Action Filters. The Authorize Attribute is fired early and may well be suited to your situation.
首先,让我们创建一个 AuthorizationFilter
First, let's create an AuthorizationFilter.
[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();
}
}
}
现在让我们来更新我们的控制器
Now let's update our Controller
[MyClassAuthorization]
public class BaseController : Controller
{
protected MyClass Foo
{
get { return (MyClass)ViewData["MyClassInstance"]; }
}
}
这篇关于获取用户身份对我的基本控制器构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!