【问题标题】:User.Identity.Name throw Object reference not set to an instanceUser.Identity.Name 抛出对象引用未设置为实例
【发布时间】:2016-09-29 08:59:48
【问题描述】:

我有这个代码

public UserProfile spUserProfileGet()
        {
            // this line throw : Object reference not set to an instance 
            var user = HttpContext.Current.User.Identity.Name;

            //...

        }

在我的 IIS 开发设置中,我有

Anonymous Authentication : Disabled
Windows Authentication : Enabled

我得到了

Object reference not set to an instance 

这是为什么呢?我之前在很多项目中使用这个类没有问题:/

HttpContext.Current.UserNULL,但为什么呢?

【问题讨论】:

  • 是的,User 对象为 NULL,但为什么呢?
  • 阅读重复的问题,它会告诉你如何解决这个问题。
  • @DavidG 在这种情况下,关于调试空引用的一般建议不太可能有帮助。如果User 为空,则表明身份验证配置存在问题。
  • 可能,原因是我在Application_BeginRequest()方法中使用它,还没有用户对象,我会检查这个

标签: asp.net-mvc-4 windows-authentication


【解决方案1】:

问题是,我从 global.asax Application_BeginRequest() 中调用了HttpContext.Current.User,它还没有包含这个对象。这是应用程序生命周期https://msdn.microsoft.com/en-us/library/ms178473.aspx 的描述,当我将代码复制到 Application_PostAuthenticateRequest,现在可以使用了。

剩下的问题是Application_PostAuthenticateRequest被触发了两次。

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多