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

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

问题描述

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

但是我无法在此处访问 User.它是 null.但是在我继承的控制器上它很好.

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.

处理这些情况的最佳方法是使用操作过滤器.授权属性提前触发并且很可能适合您的情况.

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

现在让我们更新我们的控制器

[MyClassAuthorization]
public class BaseController : Controller
{
    protected MyClass Foo
    {
        get { return (MyClass)ViewData["MyClassInstance"]; }
    }
}

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

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