【问题标题】:User.Identity.Name An object reference is required for the non-static fieldUser.Identity.Name 非静态字段需要对象引用
【发布时间】:2013-02-16 20:32:16
【问题描述】:

在我的控制器类中,我有一个私有方法,它返回使用 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'

编译时显示错误。

【问题讨论】:

  • 你能把User.Identity.Name传进去吗?或者您可以使用PrincipalContect 获取它吗?您需要传入当前用户,您可以在Page Level 获取它,如果您的方法需要DomainName\\UserName 中的用户名,则使用Split("\\") 方法在命名并传递string[1] 值

标签: c# asp.net


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    删除GetLoggedUser()方法中的static

    来自:

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

    到:

    private Account GetLoggedUser()
    {
        // your code
    }
    

    【讨论】:

    • private Account GetLoggedUser(){ } 以防 OP 不理解你.. 我学会了不要假设事情大声笑
    • +2 没问题bas 我只是说.. 我刚刚留下了一个帖子,人们确实像你一样提供了正确的答案.. OP 就像I don't understand..这是我提到它的唯一原因..我在SO 上很快学会了不要假设..lol 顺便说一句,你的答案是一个很好的答案,因为它实际上提供了正确的响应,而且你正在向 OP 展示它为什么是错误的以及在哪里他/她犯了最初的错误
    • 哈哈,日期时间老兄:)。典型的是不是...谢谢您的客气话!
    【解决方案3】:

    您无权访问静态方法中的基类实例成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多