开发者

MVC3 - Access User context in Controller base class

I have the following code in a view

@User.Identity.Name

Works fine.

The same code in a custom controller base class doesn't work. The User object is null

public class AdminBaseController : Controller
    {
        public AdminBaseController()
        {    
            string userId = User.Identity.Name;                
             //if(!AnAdmin)
                 //redirec开发者_运维问答t to UnauthorizedPage

I want to use this base class in place of System.Web.MVC.Controller as the base for all my Administration screens. This way I can redirect anybody that is not an admin (NTLM authentication).

Why the nulls? How do I get to my context? (HttpContext and something called ControllerContext are null too)


After some tinkering, things are null in the Controller constructors. The Action Methods work fine. Question still stands, but it appears I need help choosing an alternative implementation.


You should use Authorization filter, ASP.NET MVC Authorization. Also check Understanding Action Filters.

Or you can override Initialize method on Controller, User object will be initialized.


I just tried to access the 'Name'-property in a function within a controller class. That wasn't an issue and it wasn't null.

My best guess is that you can't access this object in the constructor of a controller.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜