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

标签 c# asp.net

在我的 Controller 类中,我有一个私有(private)方法,它返回使用 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 行收到此错误

An object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.User.get'

编译时显示错误。

最佳答案

你正在从一个静态方法中调用一个非静态对象/属性,它们似乎在同一个类中。在使用它之前,你需要有一个类的实例。或将方法更改为非静态。

关于c# - User.Identity.Name 非静态字段需要对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14914811/

相关文章:

c# - ASP.NET ajax c# 总是返回未定义

c# - 如何序列化包含在 System.Net.IPAddress 属性中的类?

c# - TagLib-Sharp - 重新标记文件

c# - C#修剪字符串,不考虑字符

asp.net - 身份3 SignInManager.PasswordSignInAsync()不返回任何结果

c# - asp.net webforms 中的 DISQUS 评论

c# - 如何返回 "chain"的 OrderBy() 调用以实现可重用性

c# - RemoteEndPoint 与 LocalEndPoint

c# - 将我的 View 模型绑定(bind)到 View 会导致选中所有复选框

c# - 加载外部 javascript 文件时 Colorbox 延迟打开和 "lock"