获取用户身份对我的基本控制器构造 [英] Getting User Identity on my base Controller constructor

查看:168
本文介绍了获取用户身份对我的基本控制器构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我的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()几次,那么您最终创建比方说,五个不同的控制器,这五个控制器将之前的任何创建<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.onauthorization%28v=vs.108%29.aspx\">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.

要处理这些情况,最好的方法是使用操作过滤器。在<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute%28v=vs.100%29.aspx\">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"]; }
    }
}

这篇关于获取用户身份对我的基本控制器构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆