在我的 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/