具有构造函数的非静态字段需要对象引用

object reference is required for the non-static field with constructor

 public class Auth
{

    private IBaseRepository<User> users;

    public Auth(IBaseRepository<User> users)
    {
        this.users = users;
    }

    private const string UserKey = "simpleBlog.Atuh.UserKey";

    public static User User
    {
        get
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                return null;

            var user = HttpContext.Current.Items[UserKey] as User;

            if(user == null)
            {

                 user = users.GetAll().FirstOrDefault(u => u.Name == HttpContext.Current.User.Identity.Name);

                if (user == null)
                    return null;

                HttpContext.Current.Items[UserKey] = user;

            }

            return user;
        }
    }

}

我在这部分遇到了错误,但我不知道如何解决。

user = users.GetAll().FirstOrDefault(u => u.Name == HttpContext.Current.User.Identity.Name);   

这是一个实例字段

private IBaseRepository<User> users;

但这是静态的 getter

public static User User

您无法从静态getter访问实例字段users

一种解决方案是使 users 静态,但我不知道这在您的代码的更大上下文中是否有意义。

我会让这个成为非静态的:

public static User User

public User User

class 的编写使其可以完美地接受构造函数注入。我会根据需要(瞬态)或每个网络请求实例化一次。

如果您从未使用过依赖注入,那么这是尝试它的完美方案。