简体   繁体   English

使用当前用户ID初始化ASP.NET MVC控制器

[英]Initialize ASP.NET MVC controller using current user ID

I've created an ASP.NET MVC controller which responds with data from a data repository. 我创建了一个ASP.NET MVC控制器,该控制器以数据存储库中的数据作为响应。 The repository is pretty simple (underlying EF6 backend) and the data is specific to a user. 存储库非常简单(位于EF6后端基础上),并且数据特定于用户。 So my actions typically look like this: 因此,我的动作通常如下所示:

    public class MyController : Controller
    {
        private IRepository _repository = new MyDataContextRepository();

        [HttpPost]
        [Authorize]
        public ActionResult GetMyData()
        {
            var result = _repository.GetData(Membership.GetUser().ProviderUserKey);
            return Json(result);
        }
    }

But because I'll be using the user'd ID in nearly all the calls, I'd like to initialize the repository with the current user's ID instead, like so. 但是因为几乎在所有调用中都将使用用户ID,所以我想用当前用户的ID来初始化存储库,就像这样。

    public class MyController : Controller
    {
        private IRepository _repository = new MyDataContextRepository(Membership.GetUser().ProviderUserKey);

        [HttpPost]
        [Authorize]
        public ActionResult GetMyData()
        {
            var result = _repository.GetData();
            return Json(result);
        }
    }

The problem here is that the constructor is run before the user's officially logged in, so the GetUser() looks for the username "" (user not authorized yet). 这里的问题是,构造函数是在用户正式登录之前运行的,因此GetUser()查找用户名"" (尚未授权的用户)。

Is it possible to initialize my data repository once after a user has been authenticated? 验证用户身份后,是否可以初始化我的数据存储库? Or can I only identify the user during the action method's call? 还是只能在操作方法的调用期间识别用户?

Standard practice would say that you should pass the user ID to the repository methods as a parameter, rather than basing the whole repository upon it. 标准做法是说,您应该将用户ID作为参数传递给存储库方法,而不是将整个存储库作为参数。

But if you want to do it how you are, you can wrap the _repository in a property and create it the first time it is called. 但是,如果_repository进行操作,可以将_repository包装在属性中,并在首次调用它时创建它。 A simple way to do this is to use the Lazy<T> class. 一种简单的方法是使用Lazy<T>类。 In this way the constructor will only be called the first time the repository is actually used and the User should be available then: 这样,仅在第一次实际使用存储库时才调用构造函数,然后应该可以使用User:

public class MyController : Controller
{
    private Lazy<IRepository> _repository = new Lazy<IRepository>(
        () => new MyDataContextRepository(Membership.GetUser().ProviderUserKey));

    private IRepository Repository
    {
        get { return _repository.Value; }
    }

    [HttpPost]
    [Authorize]
    public ActionResult GetMyData()
    {
        var result = Repository.GetData(); // the repository constructor will get called here
        return Json(result);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM