MVC3 User.Identity.Name 为空,Enironment.UserName 不为空
嗯,这是一个有趣的问题。我有一个在 Visual Studio 开发服务器上运行的 ASP.NET MVC3 Intranet 应用程序,没有 NTLM。我正在测试的机器上没有 AD 域。
当我尝试使用User.Identity.Name
时,它会抛出空引用异常,但是当我使用Environment.UserDomain
和Environment.UserName
时,它们填充了正确的值。
我对此感到非常困惑。我应该避免使用User.Identity.Name
,还是有原因导致它为空?
更新
我刚刚注意到,当我使用 System.Web.HttpContext.Current.User.Identity.Name
它可以工作,但仅使用 User.Identity.Name
不起作用。我错过了 using 语句吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
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 useSystem.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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Environment.UserName 只是告诉当前正在运行您的程序的用户,在您的情况下,我猜是正在运行开发服务器的用户,不需要对 asp.net 执行任何操作。
User.Identity.Name 完全不同......它告诉您当前上下文中登录者的名称。顺便说一句,您不必有 NTLM 来使用它...您可以设置 SqlMembershipProvider 或自定义成员资格提供程序并使用表单身份验证,并且无需 AD 即可正常工作。
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.