Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# User.Identity.Name非静态字段需要对象引用_C#_Asp.net - Fatal编程技术网

C# 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

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


编译时会显示错误。

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

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

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

GetLoggedUser()
方法中删除
static

发件人:

致:


你能把
User.Identity.Name
传进来吗?或者,您可以使用
PrincipalContect
获取它。您需要传入当前用户。如果您的方法需要
DomainName\\UserName
中的用户名,您也可以在
页面级别获取该用户名,并在名称上使用
Split(\\”
方法传递该用户名,然后传递
字符串[1]
value
private Account GetLoggedUser(){}
以防OP不理解您的意思。。我已经学会了不要假设lol+2不是问题,我只是说。。我刚离开一个帖子,人们像你一样给出了正确的答案。。这篇评论就像是我不明白,这是我提到它的唯一原因。。我在
上很快就学会了,所以
不要假设..哈哈,顺便说一句,你的答案很好,因为它实际上提供了正确的回答,加上你正在向OP展示错误的原因和他/她最初犯错误的地方哈哈,datetime dude:)。很典型,不是吗。。。谢谢你的好话!
private static Account GetLoggedUser()
{
    // your code
}
private Account GetLoggedUser()
{
    // your code
}