首页 文章

User.Identity.Name非静态字段需要对象引用

提问于
浏览
2

在我的控制器类中,我有私有方法,它返回使用User.Identity.Name作为参数获取的记录用户,这很好 .

private static Account GetLoggedUser()
{ 
   AccountService accService = new AccountService();
   Account userAccount = accService.GetAccountByUsername(User.Identity.Name);
   return userAccount;
}

public ActionResult Edit()
{
   var userAccount = GetLoggedUser();
...
}

问题是我在线上收到此错误 User.Identity.Name

非静态字段,方法或属性'System.Web.Mvc.Controller.User.get'需要对象引用

Error is shown at the compiling time.

3 回答

  • 3

    您正在静态方法中调用非静态对象/属性,它们看起来在同一个类中 . 你需要有一个类的实例才能使用它 . 或将方法更改为非静态 .

  • 4

    您正在以静态方法检索控制器的属性...

    删除 GetLoggedUser() 方法中的 static

    从:

    private static Account GetLoggedUser()
    {
        // your code
    }
    

    至:

    private Account GetLoggedUser()
    {
        // your code
    }
    
  • 2

    您无法以静态方法访问基类实例成员 .

相关问题