C# User.Identity.Name非静态字段需要对象引用
在我的控制器类中,我有一个私有方法,它返回记录的用户,该用户使用user.Identity.Name作为参数获取,这很好C# User.Identity.Name非静态字段需要对象引用,c#,asp.net,C#,Asp.net,在我的控制器类中,我有一个私有方法,它返回记录的用户,该用户使用user.Identity.Name作为参数获取,这很好 private static Account GetLoggedUser() { AccountService accService = new AccountService(); Account userAccount = accService.GetAccountByUsername(User.Identity.Name); return userAc
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”
编译时会显示错误。您正在从一个静态方法中调用一个非静态对象/属性,它们似乎在同一个类中。在使用该类之前,需要有该类的实例。或者将该方法更改为非静态。您无权访问静态方法中的基类实例成员。您正在静态方法中检索控制器的属性
在GetLoggedUser()
方法中删除static
发件人:
致:
你能把User.Identity.Name
传进来吗?或者,您可以使用PrincipalContect
获取它。您需要传入当前用户。如果您的方法需要DomainName\\UserName
中的用户名,您也可以在页面级别获取该用户名,并在名称上使用Split(\\”
方法传递该用户名,然后传递字符串[1]
valueprivate Account GetLoggedUser(){}
以防OP不理解您的意思。。我已经学会了不要假设lol+2不是问题,我只是说。。我刚离开一个帖子,人们像你一样给出了正确的答案。。这篇评论就像是我不明白,这是我提到它的唯一原因。。我在上很快就学会了,所以
不要假设..哈哈,顺便说一句,你的答案很好,因为它实际上提供了正确的回答,加上你正在向OP展示错误的原因和他/她最初犯错误的地方哈哈,datetime dude:)。很典型,不是吗。。。谢谢你的好话!
private static Account GetLoggedUser()
{
// your code
}
private Account GetLoggedUser()
{
// your code
}