Reputation: 44295
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)
//redirect 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)
Upvotes: 2
Views: 3454
Reputation: 166
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.
Upvotes: 0
Reputation: 5914
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.
Upvotes: 4