Search code examples
asp.net-mvc-3nullreferenceexceptionhttpcontext

MVC3 User.Identity.Name is null, Enironment.UserName is not


Well, this is an interesting problem. I have an ASP.NET MVC3 Intranet application running on the Visual Studio Development Server, no NTLM. I don't have an AD domain on the machine I'm testing on.

When I try to user User.Identity.Name, it throws a null reference exception, however when I use Environment.UserDomain and Environment.UserName, they are populated with the correct values.

I'm seriously confused about this. Should I avoid using User.Identity.Name, or is there a reason why this is null?

UPDATE

I just noticed that when I use System.Web.HttpContext.Current.User.Identity.Name it works, but just using User.Identity.Name doesn't work. Am I missing a using statement?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

Solution

  • Environment.UserName just tells the user who is currently running your program, in your case it's the user who is running the development server I guess, doesn't have to do anything with asp.net.

    User.Identity.Name is totally different... it tells you the name of the logged in person in the current context. And by the way you don't have to have NTLM to use it... you can set up SqlMembershipProvider or a custom membership provider and use forms authentication and it will work fine without AD.